React
useDebounce
Write a useDebounce hook that delays a value change.
useDebounce
useDebounce slows down a fast-changing value. Instead of searching on every keystroke, it waits a bit then acts. Ideal for search boxes.
The shape: const [debounced, setDebounced] = useState(value); useEffect(() => { const t = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(t); }, [value, delay]); return debounced;.
The principle: on every value change, a new timer is set; the previous is cleared. So debounced only updates after delay passes from the last change. This cuts API requests significantly.
Delay and dependency
Delay is usually 300-500 ms. Short delay reduces the debounce effect; long delay makes the user wait. useDebounce(value, 300) is a good start.
useEffect's dependency array should be [value, delay]. When value changes, a new timer is set; when delay changes, also reset. So the current delay is always used.
This hook becomes powerful when combined with useFetch: when the user stops typing, a search runs. This is called debounced search.
Exercise Write useDebounce
Complete the skeleton. Write a useDebounce(value, delay) hook. Define debounced state with initial value. Inside useEffect, add const t = setTimeout(() => setDebounced(value), delay); and return () => clearTimeout(t);. Dependency [value, delay]. Return debounced. Export the hook.
Show example solution
import { useState, useEffect } from "react";
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(t);
}, [value, delay]);
return debounced;
}
export default useDebounce;
Test yourself
-
Where is useDebounce useful?
- In useEffect cleanup
- On component first mount
- In CSS animations
- Reducing API requests in a search box
Show answer
Reducing API requests in a search box — It reduces API requests in search boxes.
-
Timer cleanup
To clear the previous timer, call ____.
Show answer
To clear the previous timer, call clearTimeout.
-
Match the useDebounce steps
- useState
- debounced
- setTimeout
- Delay
- clearTimeout
- Cleanup
- [value, delay]
- Deps
Next lesson: Summary - Advanced custom hooks