Common Mistakes with React's useEffect
•5 min read
useEffect is powerful, but it's arguably the hardest hook to master. The most common mistake I see is lying to the dependency array.
The Problem
If you omit a variable from the dependency array, you risk using stale data.
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
// ❌ This 'count' will always be 0 because the closure is stale
console.log(count);
}, 1000);
return () => clearInterval(id);
}, []); // ❌ Missing 'count' dependency
return <div>{count}</div>;
}The Fix
Instead of adding count to the array (which would reset the interval every second), use the functional update form:
useEffect(() => {
const id = setInterval(() => {
// ✅ Always gets the latest state
setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(id);
}, []); // ✅ Empty dependency array is now honest