Interview frequency: …
Short answer
Build a Hook that accepts a value and delay, uses useState for the deferred value and setTimeout in useEffect, and returns a cleanup function that calls clearTimeout.
Explanation
Debouncing groups repeated changes and delays work until the interaction has settled for a set period. Because of useEffect cleanup, the previous timer is cancelled whenever the value changes before the delay expires.
Code example
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}Common mistakes
- Not cleaning up the timeout, causing old delayed calls to run on top of each other.
Follow-up questions
- How do you build a Custom Hook for LocalStorage with synchronization across browser windows?
- How do you build a Custom Hook for Infinite Scroll with IntersectionObserver?