useDebounce
- React course
- Intermediate
- Lesson 7/80
- 4 min
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.
Practice 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.
Starter code
import { useState, useEffect } from "react";
// Write the useDebounce hook hereSample 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;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is useDebounce useful?
- In useEffect cleanup
- On component first mount
- In CSS animations
- Reducing API requests in a search box Correct answer
Explanation: It reduces API requests in search boxes.
2 Timer cleanup
To clear the previous timer, call ____.
To clear the previous timer, call clearTimeout.
Explanation: Cleared with clearTimeout.
3 Match the useDebounce steps
| Term | Meaning |
|---|---|
useState |
debounced |
setTimeout |
Delay |
clearTimeout |
Cleanup |
[value, delay] |
Deps |