Coding exercise: create a search box with debounce in React.

React practical coding · Freshers

Model answer

Debounce means waiting until the user stops typing for a short time before doing the work. Put the delay in a small custom hook and clean up the timer so old values never fire.

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 [q, setQ] = useState('');
  const term = useDebounce(q);
  useEffect(() => {
    if (!term) return;
    const ctrl = new AbortController();
    fetch('/api/search?q=' + encodeURIComponent(term), { signal: ctrl.signal })
      .then((r) => r.json()).then(console.log).catch(() => {});
    return () => ctrl.abort();
  }, [term]);
  return <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search" />;
}

The cleanup function clears the timer when the value changes, and AbortController cancels the older request so a slow response cannot overwrite a newer one.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

React.js Full Course: Beginner to Advanced .

Sign in to add your own answer.

More questions