Skip to content
ClapelloNotes by Barath
ReactCh 06 · 2/6
Core5 min readUpdated

React / 29

useEffect, step by step

TL;DR

Run code after React updates the screen, like fetching data or starting a timer, control how often it re-runs, and clean it up when you're done.

The shape

import { useEffect } from "react";
 
useEffect(() => {
  // setup: runs after the render is on screen
  return () => {
    // cleanup (optional): undo the setup
  };
}, [dependencies]);

Two arguments:

  1. A setup function: the side effect. It can return a cleanup function.
  2. A dependency array (optional): the values the effect uses. It decides how often the effect re-runs.

When does it run?

1 · render

React calls your component

to get the new JSX. Effects don't run here.
commit

2 · commit

React updates the DOM

only the parts that changed
paint

3 · paint

The browser draws the screen

the user sees the new UI
then

4 · effects

Cleanup, then effect

previous cleanup() ← only on a re-runeffect()
Effects run after React has updated the DOM and (usually) after the browser has painted. On a re-run, the previous effect's cleanup goes first.

React first calls your component to get JSX (render), then updates the real DOM (commit), the browser draws it (paint), and then your effect runs. So the user sees the UI first and the effect never slows down that first paint.

Counter.jsx
import { useEffect, useState } from "react";
 
export default function Counter() {
  const [count, setCount] = useState(0);
 
  useEffect(() => {
    document.title = `Clicked ${count} times`;
  }, [count]);
 
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

document.title lives outside React, so changing it is a side effect. The [count] says: "run this again whenever count changes".

The dependency array decides how often

You writeThe effect runsTypical use
useEffect(fn)After every renderRare. Usually a mistake.
useEffect(fn, [])After the first render onlyFetch once, subscribe once
useEffect(fn, [a, b])After the first render, then whenever a or b changedRe-fetch when id changes

React compares each dependency with its value from the last render using Object.is (basically ===). If nothing changed, the effect is skipped.

Try all three below. Notice that "Re-render only" runs a no-array effect even though nothing it cares about changed.

When does my effect run?

Try it

dependency array

<StrictMode> in development

useEffect(() => {log("effect runs")return () => log("cleanup")}, [count])
<Counter />count 0 · renders 1
  1. renderrender #1 · count = 0
  2. paintDOM updated, screen painted
  3. effecteffect runs
Pick a dependency array, then press the buttons. Watch which presses make the effect run, and that the old cleanup always runs before the next effect.

Cleanup: undo what you started

If your effect starts something, return a function that stops it:

Clock.jsx
import { useEffect, useState } from "react";
 
export default function Clock() {
  const [now, setNow] = useState(() => new Date());
 
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id); // stop the timer
  }, []);
 
  return <p>{now.toLocaleTimeString()}</p>;
}

React calls the cleanup at two moments:

  • Before the effect runs again, so the old timer, listener or request is stopped before a new one starts. The cleanup still sees the values from its render.
  • When the component unmounts (is removed from the page).

Forget it, and intervals stack up, event listeners pile on, and old requests write into state after you've moved on.

StrictMode runs it twice (in development)

Vite's React template wraps your app in <StrictMode>. In development only, StrictMode mounts each component, immediately unmounts it, and mounts it again. Your effect goes setup → cleanup → setup.

That's a deliberate stress test. Users really do leave a page and come back, and if your cleanup doesn't undo your setup you'll get two timers or two subscriptions. StrictMode makes that bug show up on day one. In production, effects run once.

Don't

Block the second run with a flag

const didRun = useRef(false);
useEffect(() => {
  if (didRun.current) return;
  didRun.current = true;
  startChat();
}, []);

Hides the warning sign. The real bug (no cleanup) is still there.

Do

Write the cleanup

useEffect(() => {
  const chat = startChat();
  return () => chat.stop();
}, []);

Setup, cleanup, setup now ends with exactly one chat running.

Seeing two fetches in the Network tab during development is the same thing, and it's expected. The next topic shows the cleanup for fetches.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.