Q41: What is a Stale Closure in React hooks and how do you fix it?
A stale closure happens when a hook or effect captures state/prop variables from an earlier render cycle and fails to update because dependencies were omitted from the dependency array. Fix by including updated dependencies or using functional state updates (setCount(prev => prev + 1)).
Key Takeaways
- Stale closures read outdated state values retained inside closed-over effect scopes.
- Fix using accurate dependency arrays or functional updater callbacks.
Knowledge Check
How can you safely update state based on previous state inside a timer without capturing stale closure values?