Sub topic 10
Stale closures and how to avoid them
This chapter assumes you know JavaScript closures, useState, and the dependency array and cleanup rules from the earlier chapters.
What a stale closure is
Every render creates new functions. An effect function is one of them. It "closes over" the props and state values from the render that created it. If the effect does not re-run, it keeps using those old values. This is called a stale closure.
A broken timer
This component should count up every second. It stops at 1.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds(seconds + 1); // always 0 + 1
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}The effect ran once, during the first render, where seconds was 0. Each tick calls setSeconds(0 + 1). After the first tick the state is already 1, so later ticks change nothing.
The empty array told React "this effect uses no reactive values". That claim was false.
Fix 1: list the dependency
If you add seconds to the array, the effect re-runs after every change. The cleanup clears the old interval and a new one starts with the fresh value.
useEffect(() => {
const id = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
return () => clearInterval(id);
}, [seconds]);This is correct, and it is the right default. The cost is that the interval is torn down and recreated every second. For a timer that drifts slightly. For a WebSocket connection, reconnecting on each change would be a real problem.
Fix 2: use a functional update
Often the effect only needs the previous state in order to compute the next state. Pass a function to the setter. React supplies the current value, so the effect no longer reads seconds at all.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}Now the empty array is honest. The effect uses no values from render, so it runs once and the interval is never recreated.
Choosing a fix
| Situation | Fix |
|---|---|
| The effect should re-run when the value changes | Add the value to the dependency array |
| The effect only computes the next state from the previous state | Use a functional update |
| The effect must read the latest value but should not re-run | Use a ref or an effect event (a later chapter) |
How to spot one
- A value shown on screen is correct, but a timer, listener or callback uses an older one.
- A
console.loginside an effect or callback always prints the initial value. - The dependency array is
[], yet the effect body uses props or state.
Exercise
A component registers a keydown listener in an effect with [] as dependencies. The handler calls setCount(count + 1), and the count never goes above 1. Give two ways to fix it.
Show answer
(1) Change the handler to setCount((c) => c + 1), so the effect no longer reads count and [] stays accurate. (2) Add count to the dependency array. The cleanup then removes the old listener and the effect adds a new one with the current count, at the cost of re-subscribing after every change.