Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 07 / Topic 6 of 6

useDebounce: a hook that uses cleanup correctly, internally

examples/06_use_debounce.jsx's useDebounce reuses Part 6's cleanup pattern exactly - every call restarts the wait by clearing the previous timeout before starting a new one:

// examples/06_use_debounce.jsx
export function useDebounce(value, delayMs) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timeoutId = setTimeout(() => setDebouncedValue(value), delayMs);
    return () => clearTimeout(timeoutId);
  }, [value, delayMs]);

  return debouncedValue;
}

RestaurantSearchBox, typing "p", then "pi" 300ms later, then nothing more, really keeps showing "Searching for: (nothing yet)" until 500ms after the last keystroke, then really settles on "Searching for: pi" (examples/06_use_debounce.test.jsx, driven with vi.useFakeTimers()). Nothing about the debounce timing lives in the component - a search box, a filter field, or any other input that needs this behavior can get it by calling the one hook.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide