This content originally appeared on DEV Community and was authored by Cathy Lai
What is a closure?
A closure happens when a function “remembers” variables from the scope it was created in, even after that scope has finished running.
function outer() {
let count = 0;
return function() {
count++;
return count;
};
}
const inc = outer();
console.log(inc()); // 1
console.log(inc()); // 2
The inc function closes over the variable count, keeping it alive.
Common closure bugs in React
- Stale state in intervals
useEffect(() => {
setInterval(() => {
setCount(count + 1); // ❌ count stuck at initial value
}, 1000);
}, []);
✅ Fix: use functional updates → setCount(c => c + 1)
Async race conditions
Multiple fetches can finish out of order and overwrite each other.
✅ Fix: use a cancel flag orAbortController.Event listeners
If you capture old state in a listener, it may never see new values.
✅ Fix: use refs or functional updates.
Rule of thumb
Closures = power + pitfalls. Always ask: “Which version of the variable will my function remember?”
This content originally appeared on DEV Community and was authored by Cathy Lai
Cathy Lai | Sciencx (2025-09-18T17:41:48+00:00) Closures & Common Closure Bugs. Retrieved from https://www.scien.cx/2025/09/18/closures-common-closure-bugs/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.