Closures & Common Closure Bugs

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 cou…


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

  1. Stale state in intervals
   useEffect(() => {
     setInterval(() => {
       setCount(count + 1); // ❌ count stuck at initial value
     }, 1000);
   }, []);

✅ Fix: use functional updates → setCount(c => c + 1)

  1. Async race conditions
    Multiple fetches can finish out of order and overwrite each other.

    ✅ Fix: use a cancel flag or AbortController.

  2. 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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Closures & Common Closure Bugs." Cathy Lai | Sciencx - Thursday September 18, 2025, https://www.scien.cx/2025/09/18/closures-common-closure-bugs/
HARVARD
Cathy Lai | Sciencx Thursday September 18, 2025 » Closures & Common Closure Bugs., viewed ,<https://www.scien.cx/2025/09/18/closures-common-closure-bugs/>
VANCOUVER
Cathy Lai | Sciencx - » Closures & Common Closure Bugs. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/09/18/closures-common-closure-bugs/
CHICAGO
" » Closures & Common Closure Bugs." Cathy Lai | Sciencx - Accessed . https://www.scien.cx/2025/09/18/closures-common-closure-bugs/
IEEE
" » Closures & Common Closure Bugs." Cathy Lai | Sciencx [Online]. Available: https://www.scien.cx/2025/09/18/closures-common-closure-bugs/. [Accessed: ]
rf:citation
» Closures & Common Closure Bugs | Cathy Lai | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.