Mitigating Cost: Debouncing State Updates
You'll learn how to delay state updates until the user pauses typing, dramatically reducing re-renders while keeping inputs responsive.
The Core Idea
Right now, every keystroke in a controlled input triggers setState, which causes a re-render. If you type "hello" quickly, that's 5 re-renders. Debouncing means waiting until the user stops typing for a brief moment (say, 300ms) before actually updating state. The input itself stays responsive because it's still controlled by React, but you delay the expensive parts (like filtering a huge list or making API calls) until the user pauses.
How It Works
You maintain two pieces of state:
- Immediate local state — updates instantly on every keystroke (keeps the input responsive)
- Debounced state — updates only after the user stops typing for X milliseconds
Use setTimeout inside useEffect to schedule the debounced update, and clean up the timer on every keystroke. The cleanup cancels the previous timer, so the update only happens when no new keystroke arrives within the delay window.
The Pattern
const [inputValue, setInputValue] = useState('');
const [debouncedValue, setDebouncedValue] = useState('');
// Update input immediately
const handleChange = (e) => {
setInputValue(e.target.value);
};
// Debounce the expensive state update
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(inputValue);
}, 300);
return () => clearTimeout(timer);
}, [inputValue]);
// Use debouncedValue for expensive operations
// Use inputValue for the controlled input
The input uses inputValue (instant feedback), while expensive operations use debouncedValue (updated after pause).
Key Takeaway: Debouncing state updates reduces re-renders by waiting until the user pauses, keeping inputs responsive while deferring expensive operations—ideal for search boxes and filtered lists.