How do you write a useDebounce hook?
Model answer
Keep the debounced value in state and update it in an effect after a timeout, clearing the timeout in cleanup:
useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]);
Use the debounced value to trigger a search request so you do not call the API on every keystroke.
Learn this topic
React Context API Explained: Share Data Without Passing Props in the course React.js Full Course: Beginner to Advanced.
Sign in to add your own answer.