Effects and callbacks capture values from the render where they were created.
Section: Effect Dependency Pitfalls
Stale closure pitfall
tsx
tsx
useEffect(() => {
const id = setInterval(() => {
console.log(count); // can go stale if dependencies are wrong
}, 1000);
return () => clearInterval(id);
}, [count]);Explanation
If the effect depends on `count`, include it or restructure the code to avoid stale reads.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Effect Dependency Pitfalls
Move non-reactive logic out of effects
Keep effects focused on synchronization.
Memoize objects used in dependencies
Avoid recreating dependency objects every render when identity matters.
Perform event-specific work in event handlers
Do not move user-triggered logic into effects unnecessarily.
Call hooks only at the top level
Do not call hooks in conditions, loops, or nested functions.
Do not memoize everything
Memoization has a cost; use it when it solves a concrete problem.
Call hooks only from components or custom hooks
Do not call hooks from regular utility functions.