The useEffect Hook
Side effects, the dependency array, cleanup functions, and avoiding infinite re-render loops.
What you'll learn
- What side effects are and why they need useEffect
- The dependency array and when the effect re-runs
- Cleanup functions for subscriptions and timers
- Common pitfalls like missing dependencies and infinite loops
Concept
What Is useEffect?
React components should be pure functions of their props and state — they should not have side effects during render. Side effects include fetching data, subscribing to events, setting timers, manually changing the DOM, and logging. The useEffect hook lets you perform these side effects after the render is committed to the screen. Think of it as React's way of saying "the component has rendered, now you can do things that affect the outside world."
The Dependency Array
The second argument to useEffect is the dependency array. It controls when the effect re-runs. An empty array [] means the effect runs only once after the initial mount. No array at all means the effect runs after every render. An array with values [a, b] means the effect runs after the initial render and whenever a or b changes. Getting the dependency array right is crucial — missing dependencies cause stale closures, and extra dependencies cause unnecessary re-runs.
Cleanup Functions
If your effect creates a resource that needs cleaning up — a subscription, a timer, an event listener, a WebSocket connection — you return a cleanup function from the effect. React calls this cleanup before re-running the effect and when the component unmounts. This prevents memory leaks and stale callbacks. For example, if you set up an interval, return () => clearInterval(id) to clear it.
Avoiding Infinite Loops
A common mistake is updating state inside an effect that has that same state in its dependency array, causing an infinite render loop. If you must update state in an effect, make sure the effect does not depend on the state it updates, or add a guard condition. Consider whether the logic truly belongs in an effect or if it can be computed during render or moved to an event handler.
Example
import { useState, useEffect } from "react";
function WindowSize() {
const [width, setWidth] = useState(window.innerWidth);
const [count, setCount] = useState(0);
// Effect with cleanup — runs on mount and unmount only.
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleResize);
// Cleanup function removes the listener.
return () => window.removeEventListener("resize", handleResize);
}, []); // Empty deps = run once.
// Effect that depends on count — re-runs when count changes.
useEffect(() => {
document.title = `Clicked ${count} times`;
}, [count]);
return (
<div>
<p>Window width: {width}px</p>
<button onClick={() => setCount(c => c + 1)}>Click count: {count}</button>
</div>
);
}
The first effect sets up a resize listener with cleanup and an empty dependency array (run once). The second updates the document title whenever count changes.
Try it
- Code Diff
Compare effect logic before and after fixing dependency issues.
- JSON Formatter
Format API response data fetched inside useEffect.
Common mistakes
The mistake
Forgetting to include dependencies in the dependency array
The fix
If your effect uses a prop or state value, include it in the dependency array. Otherwise, the effect captures a stale value. Use the eslint-plugin-react-hooks exhaustive-deps rule to catch this.
The mistake
Updating state in an effect that depends on that same state
The fix
This causes an infinite render loop. Add a guard condition, remove the state from deps, or move the logic to an event handler. Ask whether the effect is truly necessary.
Practice The useEffect Hook
14 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.