§ GARDEN · JAVASCRIPT · CLASS OPEN
NODE FILE · ENTRY
Closures Are Not Magic
FILED UNDER · JAVASCRIPT
①Read
②Meta
What closures actually are, why they capture by reference, and the stale closure bugs that trip up React devs.
A closure is a function that remembers the variables from the scope where it was created, even after that scope has exited. That's the entire definition. Every function in JavaScript is a closure. The 'magic' people attribute to closures is just lexical scoping doing exactly what it's supposed to do.
The Stale Closure Problem
In React, closures cause the most confusion inside useEffect and event handlers. A callback created during render 'closes over' the state value at that render. If state updates but the callback isn't recreated, it still sees the old value. This is why the dependency array exists — it tells React when to create a fresh closure.
DTNRWORKSHOP ARMAMENTSSN 2012.OTT.0176