Sub topic 3
Stale Closures and Reliable Effects
Assume you know function components, JSX, useState, JavaScript closures, Promises, and fetch. A closure is a function together with the variables captured from its surrounding scope. In an effect, a closure can capture an old prop or state value.
Stale closures
The dependency array must include every reactive value that the effect reads. Otherwise, the effect may keep using an old value.
import { useEffect, useState } from "react";
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((current) => current + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds</p>;
}The functional state update avoids reading a captured seconds value. If an effect needs a changing prop, include that prop in its dependencies.
Objects and functions as dependencies
Objects and functions are compared by reference. Creating either during rendering can make an effect run on every render.
function Search({ query }) {
useEffect(() => {
// Fetch results for query.
}, [query]);
}Prefer primitive dependencies. If an object or function is required, move its creation inside the effect, memoize it when appropriate, or redesign the effect. Do not silence the dependency linter without understanding the dependency.
Strict Mode and custom hooks
In development, React Strict Mode may start an effect, clean it up, and start it again. This exposes missing cleanup and unsafe assumptions. Effects should tolerate setup followed immediately by cleanup.
Reusable synchronization logic belongs in a custom hook:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const update = () => setWidth(window.innerWidth);
window.addEventListener("resize", update);
return () => window.removeEventListener("resize", update);
}, []);
return width;
}Debugging and latest values
Enable the hooks lint rule. It usually identifies missing dependencies and stale closures. Log effect setup and cleanup to find unexpected reruns.
When an effect must run once but read the newest value, store that value in a ref:
const latest = useRef(value);
latest.current = value;The effect can read latest.current without adding value as a dependency. Use this sparingly because it bypasses React’s dependency model.
When timing matters
useLayoutEffect runs after the DOM is committed but before the browser paints. Use it for measuring layout or preventing visible flicker. Prefer useEffect for network requests, subscriptions, and ordinary synchronization because it does not block painting.
Exercise
Why can an empty dependency array cause a stale closure?
Show answer
The effect runs once and keeps the values captured during that render. Use a functional update, add the changing dependency, or deliberately read a ref containing the latest value.