useEffect
Learn how the React useEffect hook syncs a component with external systems, including the dependency array, cleanup and when you do not need an effect.
On this page
1. What is useEffect?
Rendering should only calculate JSX. Work that has to happen after rendering, like setting up a subscription or changing document.title, goes into an effect.
2. Why does it matter?
| Side effect inside render | Inside useEffect |
|---|---|
| Runs again and again on every render | Runs only when dependencies change |
| Render is slow and impure | Render stays pure, the effect runs after commit |
| You forget to close subscriptions | The cleanup function runs for you |
| Memory leaks | Cleanup happens on unmount |
3. Where is it used?
| Use case | What the effect does |
|---|---|
| Timers | Start setInterval and clear it in cleanup |
| Browser events | A window resize or online/offline listener |
| WebSocket / chat | Open and close a connection |
| Third-party widget | Attach a map or chart library to a DOM node |
| Document title | Set the tab title from state |
4. How does it work?
| Dependency array | When the effect runs |
|---|---|
[a, b] | The first time, then whenever a or b changes |
[] | Only on mount (and cleanup on unmount) |
| No array at all | After every render (usually wrong) |
5. Code example
Timer with cleanup
import { useEffect, useState } from "react";
export default function Clock() {
const [time, setTime] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{time.toLocaleTimeString()}</p>;
}Syncing with a prop
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect();
}, [roomId]);
return <h2>Room: {roomId}</h2>;
}How does the code work?
| Part | Meaning |
|---|---|
useEffect(() => ..., []) | The interval starts on mount |
return () => clearInterval(id) | Cleanup, which stops the interval on unmount |
[roomId] | When the room changes, disconnect from the old one and connect to the new one |
createConnection | An outside system, which is why an effect is needed |
You might not need an effect
A lot of code that gets written in effects is not really effect work. Effects are only for outside systems.
| Situation | Use this instead of an effect |
|---|---|
| Calculating a value from props or state | Calculate it directly during render |
| An expensive calculation | useMemo (or React Compiler) |
| Doing something on a user click | Do it in an event handler |
| Resetting state when a prop changes | Give the component a key |
| Data fetching | A framework, TanStack Query or use() |
function Cart({ items }) {
const total = items.reduce((sum, item) => sum + item.price, 0);
return <p>Total: Rs. {total}</p>;
}Here, creating state and an effect for total would only add extra re-renders and bugs. Calculating it directly is enough.
6. Common mistakes
Mistake: Hiding values from the dependency array so the effect runs less
Why? The effect keeps seeing old props or state (a stale closure) and works with wrong data.
Better: Put every reactive value the effect uses in the dependencies. Move values that should not trigger the effect into useEffectEvent.
Mistake: Setting state in an effect when that same state is a dependency
Why? Setting causes a re-render, the re-render runs the effect, the effect sets again: an infinite loop.
Better: Calculate derived values in render, or use an updater function to remove the dependency.
Mistake: Not writing a cleanup function
Why? Intervals, listeners or connections keep running after unmount, causing memory leaks and duplicate events.
Better: An effect that starts something should also stop it in its return function.
Mistake: Putting button click logic inside an effect
Why? An effect runs because of rendering, not because of a user action. The logic can run at the wrong time or twice.
Better: Do the work for a user action in an event handler.
7. What to learn before and after
| Stage | Chapters |
|---|---|
| Before | Rules of Hooks, State with useState |
| After | useEffectEvent, Custom Hooks, Data Fetching |
| Related | useRef, useMemo & useCallback |
Final quick revision
| Point | Detail |
|---|---|
| Job | Sync with an external system |
| When it runs | After commit |
| Dependencies | Every reactive value the effect uses |
| Cleanup | The returned function, on re-run and on unmount |
| First question | Do I even need an effect? |