Hooks & APIs: useEffect & Cleanups
useEffect & Cleanups: Manage external systems, event subscriptions, and timer cleanups without race conditions.
In modern React, useEffect is not a lifecycle hook. It is not syntactic sugar for componentDidMount, componentDidUpdate, and componentWillUnmount.
Framing useEffect around class component lifecycles leads directly to common production regressions: infinite render loops, stale closures, memory leaks, and asynchronous race conditions.
The modern mental model for useEffect is synchronization with external systems:
- An effect declares how to synchronize an external, non-React system (such as the browser DOM, a third-party widget, a WebSocket connection, or an external API) with the current props and state of your component—and how to tear down that synchronization when those inputs change or when the component unmounts.
## 1. Anatomy of an Effect: Setup & Teardown
- **An effect consists of two symmetrical halves:** a setup function and an optional cleanup (teardown) function.
```ts
useEffect(() => {
// 1. SETUP: Connect or synchronize with the external system
const subscription = dataSource.subscribe(id);
// 2. CLEANUP: Disconnect, abort, or reset
return () => {
subscription.unsubscribe();
};
}, [id]); // 3. DEPENDENCY BARRIER: Inputs that govern re-synchronization
```
### The Exact Execution Order
When dependencies change, React runs the previous effect's cleanup first, before running the next effect's setup:
```text
State changes: id = 'A' ──> id = 'B'
```
## 1. Component renders with id = 'B'
## 2. Browser paints the updated screen
## 3. CLEANUP runs for id = 'A' (tears down old connection)
## 4. SETUP runs for id = 'B' (establishes new connection)
This sequence prevents resource leaks and guarantees that stale connections are torn down before new ones initialize.
## 2. Race Conditions: The Silent Network Killer
A race condition occurs when multiple asynchronous network requests are triggered in sequence but resolve out of order due to variable network latency.
### The Bug Scenario
User searches for "cat" (Request 1 fires, takes 800ms).
User quickly amends the search to "caterpillar" (Request 2 fires, takes 200ms).
- **Request 2 completes first:** results for "caterpillar" render on screen.
- **Request 1 completes later:** results for "cat" arrive and overwrite the UI.
```text
Outcome: The search input displays "caterpillar", but the list displays results for "cat".
t = 0ms [Fetch "cat" ───────────────────────────────────────> Resolves: "cat"] ❌ Overwrites!
t = 150ms [Fetch "caterpillar" ──────> Resolves: "caterpillar"]
(Rendered temporarily)
```
### Solution A: The Boolean Ignore Flag (Simple & Universal)
Use a local mutable flag inside the effect closure. When the effect tears down, flip the flag so late-arriving promises are safely ignored:
```ts
import { useState, useEffect } from 'react';
export function SearchResults({ query }: { query: string }) {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
// Flag scoped strictly to this execution cycle
let ignore = false;
setIsLoading(true);
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then((results) => {
// If the query changed while waiting, ignore the stale response
if (!ignore) {
setData(results);
setIsLoading(false);
}
})
.catch((err) => {
if (!ignore) {
console.error(err);
setIsLoading(false);
}
});
// Cleanup: runs immediately when `query` changes or component unmounts
return () => {
ignore = true;
};
}, [query]);
return (
(null);
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
async function loadUser() {
try {
const res = await fetch(`/api/users/${userId}`, { signal });
const data = await res.json();
setUser(data);
} catch (err: unknown) {
// Aborted requests throw an 'AbortError'; do not treat as an error
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
console.error('Fetch failed:', err);
}
}
loadUser();
// Abort the pending network call if userId changes or component unmounts
return () => {
controller.abort();
};
}, [userId]);
return (null);
const chartInstanceRef = useRef(null);
useEffect(() => {
if (!canvasRef.current) return;
// 1. Initialize external imperative system
chartInstanceRef.current = new Chart(canvasRef.current, {
type: 'line',
data: {
labels: dataPoints.map((_, i) => `T${i}`),
datasets: [{ data: dataPoints }],
},
});
// 2. Teardown: destroy external instance to release memory and canvas bindings
return () => {
chartInstanceRef.current?.destroy();
chartInstanceRef.current = null;
};
}, [dataPoints]);
return ;
}
```
## 4. Timers and Intervals: Avoiding Stale Closures
Timers inside useEffect frequently fall into the stale closure trap if dependencies or state updaters are misconfigured.
### 4.1 The Stale Closure Anti-Pattern
```ts
// ❌ BROKEN: Captures `seconds = 0` forever
export function BrokenTimer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
// Stale closure: `seconds` is read as 0 on every tick
setSeconds(seconds + 1);
}, 1000);
return () => clearInterval(id);
}, []); // Empty deps keeps the initial closure forever
return
{isLoading &&
);
}
```
### Solution B: Native Request Cancellation (AbortController)
While the boolean flag prevents stale state updates, the browser still spends bandwidth downloading the unwanted payload. The industry standard is cancelling the in-flight HTTP request using the browser's native AbortController:
```ts
import { useState, useEffect } from 'react';
export function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useStateLoading...
}-
{data.map((item) => (
- {item} ))}
{user ? user.name : 'Loading...'}
;
}
```
## 3. Subscriptions & Browser Event Cleanups
When subscribing to browser events (resize, scroll, keyboard listeners) or streaming sockets, omitting a cleanup causes listener stacking. Every re-render registers an additional listener, rapidly degrading memory and CPU performance.
### 3.1 Document & Window Listeners
```ts
import { useState, useEffect } from 'react';
export function WindowDimensions() {
const [width, setWidth] = useState(() => window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
// Mandatory cleanup: removes the listener when component unmounts
return () => {
window.removeEventListener('resize', handleResize);
};
}, []); // Empty array: setup once on mount, cleanup once on unmount
return Window width: {width}px
; } ``` ### 3.2 Third-Party Widget Integration (Leaflet, Charts, Video Players) External libraries mutate the real DOM directly. Your effect must instantiate the instance on mount and destroy it on unmount: ```ts import { useEffect, useRef } from 'react'; import Chart from 'chart.js/auto'; export function MetricChart({ dataPoints }: { dataPoints: number[] }) { const canvasRef = useRef{seconds}
; // Advances to 1, then stops! } ``` ### 4.2 The Solution: Functional State Updates Bypass closure dependencies entirely by passing an updater callback to the state setter. The setter automatically supplies the latest committed state value: ```ts // ✅ CORRECT: Zero stale closure dependence export function WorkingTimer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const id = setInterval(() => { setSeconds((prev) => prev + 1); // Reads latest queue state }, 1000); // Guaranteed cleanup on unmount return () => clearInterval(id); }, []); // Truly runs once; no stale state references return{seconds}
; } ``` ## 5. Why Does StrictMode Run Effects Twice? In local development (npm run dev), React wraps the root application in <React.StrictMode>. This causes every effect to execute in this sequence upon mount: - $$\text\{Mount\} \longrightarrow \text\{Setup Effect\} \longrightarrow \text\{Cleanup Effect\} \longrightarrow \text\{Setup Effect\}$$ - The Diagnostic Purpose React intentionally runs this mount-unmount-remount cycle to verify that your effect is symmetrical and resilient: - If your effect connects to a WebSocket without closing it in cleanup, StrictMode creates two open connections immediately—exposing the bug during development. - If your effect attaches a global window event listener without removing it, StrictMode creates duplicate listeners immediately. - If your cleanup logic is correct, the temporary teardown leaves no trace, and the second setup restores full synchronization cleanly. - **Never bypass this with a ref:** Avoid patterns like if (!hasRun.current) to suppress the second run. That hides the warning without resolving the underlying leak. Fix the cleanup function instead. ## 6. The Dependency Array Contract - **The dependency array tells React:** "Re-run this effect only if one of these values has changed by Object.is reference equality." | Syntax | Execution Timing | Primary Use Case | | --- | --- | --- | | useEffect(() => \{ ... \}) (No deps) | Runs after every single render pass. | Rarely used; usually indicates an omitted dependency array. | | useEffect(() => \{ ... \}, []) (Empty deps) | Runs once on mount; cleans up once on unmount. | Static global event listeners, one-time widget instantiation. | | useEffect(() => \{ ... \}, [a, b]) | Runs on mount, and re-runs whenever a or b changes. | Data synchronization, filtered searches, dynamic socket rooms. | ### The Golden Rule of Dependencies Do not lie to the dependency array. Every reactive value (props, state, or variables derived from them) referenced inside the effect function must be declared in the dependency array. If the linter (eslint-plugin-react-hooks) flags a missing dependency: - Include it in the array. If including it causes an infinite loop, refactor: - Move the variable/function inside the effect. - Move it outside the component entirely if it has no reactive inputs. - Wrap the function in useCallback or object in useMemo. - Use a functional state updater (setVal(prev => ...)). ## 7. You Might Not Need an Effect Modern React strongly discourages using useEffect for operations that do not involve external synchronization: | Anti-Pattern Scenario | Incorrect useEffect Approach | Idiomatic Modern React Solution | | --- | --- | --- | | Transforming data for render (filtering a list, calculating totals) | Storing filtered results in a separate state via useEffect. | Calculate it directly during render (or wrap in useMemo if computationally expensive). | | Handling user actions (submitting a form, button clicks) | Setting a flag state, then triggering an API call in useEffect. | Execute directly inside the event handler (onSubmit, onClick). | | Resetting state when a prop changes (e.g., selecting a new user ID) | Listening to userId in useEffect and calling setFormState(initial). | Pass a unique key prop to the component (<UserForm key="\{userId\}"/>) to force a clean remount. |