Skip to content
HooksChapter 16 / 37Intermediate5 min read

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 renderInside useEffect
Runs again and again on every renderRuns only when dependencies change
Render is slow and impureRender stays pure, the effect runs after commit
You forget to close subscriptionsThe cleanup function runs for you
Memory leaksCleanup happens on unmount

3. Where is it used?

Use caseWhat the effect does
TimersStart setInterval and clear it in cleanup
Browser eventsA window resize or online/offline listener
WebSocket / chatOpen and close a connection
Third-party widgetAttach a map or chart library to a DOM node
Document titleSet the tab title from state

4. How does it work?

The effect lifecycle
The component renders
React updates the screen (commit)
The effect runs
A dependency changed: cleanup first, then the new effect
Final cleanup on unmount
Dependency arrayWhen the effect runs
[a, b]The first time, then whenever a or b changes
[]Only on mount (and cleanup on unmount)
No array at allAfter every render (usually wrong)

5. Code example

Timer with cleanup

jsx
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

jsx
function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return <h2>Room: {roomId}</h2>;
}

How does the code work?

PartMeaning
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
createConnectionAn 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.

SituationUse this instead of an effect
Calculating a value from props or stateCalculate it directly during render
An expensive calculationuseMemo (or React Compiler)
Doing something on a user clickDo it in an event handler
Resetting state when a prop changesGive the component a key
Data fetchingA framework, TanStack Query or use()
jsx
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

Final quick revision

PointDetail
JobSync with an external system
When it runsAfter commit
DependenciesEvery reactive value the effect uses
CleanupThe returned function, on re-run and on unmount
First questionDo I even need an effect?