MyInternships.in

Data Fetching & APIs

React Debouncing API Calls

Debouncing delays an action until the input has been quiet for a set period. In a search box it means one request after the user stops typing rather than one per keystroke.


What is Debouncing API Calls in React?

Debouncing delays an action until the input has been quiet for a set period. In a search box it means one request after the user stops typing rather than one per keystroke.

Debouncing API Calls example

Debounce with a custom hook
JSX
function useDebounce(value, delay = 400) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

function Search() {
  const [input, setInput] = useState('');
  const query = useDebounce(input, 400);

  useEffect(() => {
    if (query) searchJobs(query);
  }, [query]);

  return <input value={input} onChange={e => setInput(e.target.value)} />;
}

How this works

Each keystroke clears the pending timeout and starts a new one, so the state only settles once typing pauses. The input itself stays instant because it reads the undebounced value.

Key points to remember

  • Debounce is about frequency; throttle caps the rate to one call per interval.
  • 300–500 ms feels responsive for search; longer starts to feel broken.
  • Combine with request cancellation for correctness under slow networks.

Common mistakes with Debouncing API Calls

  • Debouncing the input’s own value, which makes typing visibly laggy.
  • Forgetting clearTimeout in the cleanup, which fires every intermediate value anyway.

React Debouncing API Calls— Interview Questions & FAQs

What is the difference between debounce and throttle?+

Debounce waits until activity stops and then runs once — good for search input. Throttle runs at most once per interval regardless of activity — good for scroll and resize handlers.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships