Effects

Synchronizing with the outside world, and when not to.

Builds on Refs.

Render has to be pure. Event handlers run when the user does something. But some code needs to run simply because a component is on the screen: connect to a chat room while the room is visible, subscribe to a window event, start an animation, keep a non-React widget in sync with props. That code can't go in render, and there's no event to hang it on.

Effects are the place for it. You built the mechanism in Effects from scratch: during render the component records an effect and its dependencies; after the commit React runs the ones whose dependencies changed, running the previous cleanup first. This chapter is about using the real useEffect well, which mostly means understanding one idea (effects synchronize React state with something outside React) and knowing the many cases where you don't need an effect at all. It's the most misused hook, so it's also one of the most asked about.

The problem: setup without teardown#

Here's a chat room that connects when it's shown. The fake connection keeps a count of open connections, so you can see leaks. The sandbox runs in StrictMode. Switch rooms a few times.

An effect that never cleans up
import { useEffect, useState } from "react";
import { createConnection } from "./chat";

function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    // No cleanup: nothing ever disconnects.
  }, [roomId]);
  return <h3>Welcome to #{roomId}</h3>;
}

export default function App() {
  const [roomId, setRoomId] = useState("general");
  return (
    <>
      <select value={roomId} onChange={(e) => setRoomId(e.target.value)}>
        <option value="general">general</option>
        <option value="travel">travel</option>
        <option value="music">music</option>
      </select>
      <ChatRoom roomId={roomId} />
    </>
  );
}
Nothing logged yet.

The first load already shows two open connections, and every room change adds one. In a real app each of those would be a live socket receiving messages for rooms the user left. Notice how StrictMode made the leak visible before you touched anything. We'll come back to why it does that.

Effects synchronize with the outside world#

The fix is to say how to stop, not just how to start:

Setup, cleanup and dependencies
import { useEffect, useState } from "react";
import { createConnection } from "./chat";

function ChatRoom({ roomId }: { roomId: string }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    return () => connection.disconnect(); // cleanup
  }, [roomId]); // re-synchronize when roomId changes
  return <h3>Welcome to #{roomId}</h3>;
}

export default function App() {
  const [roomId, setRoomId] = useState("general");
  const [show, setShow] = useState(true);
  return (
    <>
      <select value={roomId} onChange={(e) => setRoomId(e.target.value)}>
        <option value="general">general</option>
        <option value="travel">travel</option>
        <option value="music">music</option>
      </select>{" "}
      <button onClick={() => setShow((s) => !s)}>{show ? "Close chat" : "Open chat"}</button>
      {show && <ChatRoom roomId={roomId} />}
    </>
  );
}
Nothing logged yet.

Now open never goes above 1. Read the effect as a description, not as a lifecycle: "while this component is shown with some roomId, be connected to that room." React makes it true. When roomId changes, it stops synchronizing with the old room (cleanup, with the old roomId from that render's closure) and starts with the new one (setup). When the component goes away, it stops.

That's the mental model react.dev pushes, and it's the one to use in interviews: an effect is not "run on mount" or "run on update". It's a synchronization process with a start and a stop, which React may run many times. Thinking in mount/update/unmount is how people write effects that work once and leak on the second room.

useEffect(setup, dependencies?):

  • setup runs after the commit. It may return a cleanup function.
  • Before running setup again (because dependencies changed) and when the component unmounts, React runs the previous cleanup.
  • Typing pattern: the setup returns void or a cleanup function. That's why useEffect(async () => ...) is a type error: an async function returns a promise, and React would treat it as a cleanup. Define an async function inside and call it.
The effect lifecycle
MountrenderpurecommitDOM + refslayout effectsetuppainteffectsetupUpdaterendernew depscommitDOM + refslayout effectcleanup, setuppainteffectcleanup, setupUnmountlayout effectcleanupcommitremove DOMeffectcleanupStrictModerender ×2commitsetupcleanupsimulatedsetupagaintime →
Step 1 of 8

Mount, render: React calls your component. Effects are only declared here; nothing runs yet.

Dependencies#

The dependency array tells React when to re-synchronize. React compares each item with its previous value using Object.is, the same check you implemented in your toy.

useEffect(() => { /* ... */ });               // after every commit
useEffect(() => { /* ... */ }, []);           // once after mount (and cleanup on unmount)
useEffect(() => { /* ... */ }, [roomId]);     // when roomId changes

The rule that makes this manageable: you don't choose your dependencies. Your code does. Every reactive value the effect reads (props, state, and anything computed from them during render) must be listed. The react-hooks/exhaustive-deps lint rule in eslint-plugin-react-hooks checks this, and it's right far more often than the people who suppress it.

If you don't want an effect to re-run for some value, don't fight the linter. Change the code so the effect doesn't need the value:

  • Move objects and functions that are only used by the effect inside the effect. An object created during render is a new object every time, so as a dependency it re-runs the effect after every render.
  • Use an updater function instead of reading state: setCount(c => c + 1) doesn't need count.
  • If the value is read by logic that isn't part of the synchronization, like a theme color in a notification, use an Effect Event (below).
  • Values that never change, like a module constant or a state setter, don't need to be listed. Setters and dispatch are stable, and the linter knows it.

Stale closures in effects#

An effect closes over the render it was created in, like any other function (State). If its dependency list lies, it keeps using old values.

PredictA counter that stops at 1

The linter would flag this. What does the counter show after three seconds, and why? Then fix it without adding count to the dependencies.

import { useEffect, useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return <h2>{count}</h2>;
}

The order effects run in#

Interviewers like "in what order do these effects run?" because the answer shows you know how a commit works. Click Update and read the console:

Effect order across a parent and child
import { useEffect, useLayoutEffect, useState } from "react";

function Child({ n }: { n: number }) {
  useLayoutEffect(() => {
    console.log("child layout setup", n);
    return () => console.log("child layout cleanup", n);
  }, [n]);
  useEffect(() => {
    console.log("child effect setup", n);
    return () => console.log("child effect cleanup", n);
  }, [n]);
  return <p>Child sees {n}</p>;
}

export default function App() {
  const [n, setN] = useState(0);
  useEffect(() => {
    console.log("parent effect setup", n);
    return () => console.log("parent effect cleanup", n);
  }, [n]);
  return (
    <>
      <button onClick={() => setN(n + 1)}>Update</button>
      <Child n={n} />
    </>
  );
}
Nothing logged yet.

Three rules explain the log:

  1. Children before parents. The commit walks the tree and finishes a child before its parent, so a child's effects run first. A parent's effect can rely on its children's effects (and refs) already being set up.
  2. Layout effects before passive effects. Every useLayoutEffect runs synchronously during the commit, before the browser paints. useEffect runs after, usually after paint. The useLayoutEffect section below covers when that matters.
  3. All cleanups before any setup. On an update, React runs every cleanup that's due in the commit (child, then parent) before it runs any new setup. No effect's setup ever sees another component's previous setup still active.

The same order holds for unmounting: cleanups run child first.

StrictMode runs your effects twice, and why#

In development, <StrictMode> does an extra cycle for every component as it mounts: setup, then cleanup, then setup again, as if the component were shown, removed and shown again immediately. (It also double-calls renders, as you saw in Components and props.) React 19.3 React 19.3 extends this to components that mount during hydration too.

Why would React deliberately do this?

  1. To find missing cleanups. If setup, cleanup, setup leaves things in a different state than one setup would, your cleanup is wrong. The leaky chat room showed two connections on the first load; the fixed one shows connect, disconnect, connect and ends with one. A user would hit the same bug by navigating away and back, just later and less visibly.
  2. Because React really does unmount and remount state-preserving UI. Features like <Activity> (Activity and View Transitions) hide a subtree by destroying its effects and later recreate them with the state kept. Fast Refresh does the same during development. Effects that tolerate being cleaned up and set up again are effects that work with those features.

It only happens in development. The right response is almost never "prevent the second run" with a ref flag like didRun. It's to write the cleanup that makes the second run harmless: disconnect what you connected, unsubscribe what you subscribed, clear what you scheduled, ignore results of a request you no longer care about. For code that truly must run once per app load (initializing an analytics SDK), put it at module level or behind a module-level flag, outside any component.

PredictThe StrictMode log

In the fixed chat sandbox above (with StrictMode), what exactly is logged on first load, before you touch anything?

Fetching data, and race conditions#

Fetching in an effect is common, and it has a classic bug. Responses don't arrive in the order you asked for them. If the user types "r" and then "re", and the "r" request is slower, the "r" results arrive last and overwrite the right ones.

The fix uses cleanup. Each effect run either ignores its result if it has been superseded, or aborts its request:

useEffect(() => {
  let ignore = false;
  fakeFetch(`/books?q=${query}`).then((data) => {
    if (!ignore) setResults(data);
  });
  return () => {
    ignore = true; // this run is out of date
  };
}, [query]);

Each run has its own ignore variable. When query changes, React runs the old cleanup, which flips the old run's flag, so its late response is dropped. With AbortController you also cancel the network work itself:

useEffect(() => {
  const controller = new AbortController();
  fakeFetch(`/books?q=${query}`, { signal: controller.signal })
    .then(setResults)
    .catch((err) => {
      if (err.name !== "AbortError") setError(err);
    });
  return () => controller.abort();
}, [query]);
Fix itSearch results from the wrong query

Searches for one letter are slow in this fake API, longer ones are fast. Type r, then quickly e. The list first shows results for "re", then gets overwritten by the late results for "r". Fix the effect so the list always matches the latest query.

import { useEffect, useState } from "react";
import { fakeFetch, books } from "guide-tools";

type Book = (typeof books)[number];

export default function Search() {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<Book[]>([]);

  useEffect(() => {
    if (!query) return;
    // One letter is slow, more letters are fast: a guaranteed race.
    const delay = query.length === 1 ? 900 : 150;
    fakeFetch(`/books?q=${encodeURIComponent(query)}`, { delay }).then((data) => {
      setResults(data as Book[]);
    });
  }, [query]);

  return (
    <>
      <input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search books" />
      <p>
        {query ? results.length : 0} results for "{query}"
      </p>
      <ul>{query ? results.map((b) => <li key={b.id}>{b.title}</li>) : null}</ul>
    </>
  );
}

Even with the race fixed, hand-written fetching effects miss a lot: caching, deduplication, retries, preloading, avoiding network waterfalls, server rendering. That's why react.dev recommends a framework's data loading or a library. Suspense and use and Server state cover those. Know the race and its fix anyway; it's a favorite interview question.

Event handlers versus effects#

Both can contain side effects. The question that decides which one to use is: what caused this code to run?

  • If it's a specific interaction (the user clicked Buy, submitted a form, pressed a key), it belongs in the event handler. You know exactly what happened.
  • If it's the component being displayed with certain values (the chat room is on screen for room X, the page is showing product Y), it belongs in an effect. It should happen no matter how you got there.
function ProductPage({ productId }: { productId: string }) {
  // Displayed: log a page view whenever this product is shown.
  useEffect(() => {
    logVisit(productId);
  }, [productId]);

  // Interaction: send the POST because the user clicked.
  function handleBuy() {
    post("/api/buy", { productId });
    showNotification("Added to cart");
  }
  // ...
}

Put post("/api/buy") in an effect that watches a wasBought flag and you've built a bug: the request may re-fire on remount, under StrictMode, or when something else changes the flag. Event-specific logic belongs in events. Effects are reactive: they re-run whenever the values they read change, while handlers run once per interaction.

You might not need an effect#

Most effects in real codebases shouldn't exist. An effect that only reads props or state and sets other state is usually doing a calculation the slow way: render with stale data, commit, run the effect, set state, render again.

Derived state through an effect renders twice
import { useEffect, useState } from "react";
import { books, Rendered } from "guide-tools";

type Book = (typeof books)[number];

function WithEffect({ query }: { query: string }) {
  const [visible, setVisible] = useState<Book[]>(books);
  useEffect(() => {
    setVisible(books.filter((b) => b.title.toLowerCase().includes(query.toLowerCase())));
  }, [query]);
  return <Rendered label="Effect + state">{visible.length} books</Rendered>;
}

function Derived({ query }: { query: string }) {
  const visible = books.filter((b) => b.title.toLowerCase().includes(query.toLowerCase()));
  return <Rendered label="Derived during render">{visible.length} books</Rendered>;
}

export default function App() {
  const [query, setQuery] = useState("");
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type to filter" />
      <WithEffect query={query} />
      <Derived query={query} />
    </>
  );
}

Type a few letters. The effect version renders twice per keystroke (once with the old list, once after the effect sets the new one); the derived version renders once and is never out of date. The common cases, all from react.dev's guide:

  • Transforming data for rendering: compute it during render. If it's expensive, useMemo (Memoization).
  • Resetting all state when a prop changes: pass a key (State), not an effect that calls setters.
  • Adjusting some state when a prop changes: usually you can derive instead (store a selected id, not a copy). If not, set it during render guarded by a comparison with the previous value, not in an effect.
  • Responding to an event: do it in the handler. "When the user clicks, then the effect sees the flag and..." is a handler with extra steps.
  • Notifying a parent about a change: call the parent's callback in the same handler that changes your state, or lift the state up.
  • Chains of effects that set state to trigger other effects: compute the next state in one handler.
  • Initializing the app once: module level, not an effect.
  • Subscribing to an external store: useSyncExternalStore (Custom hooks).

What's left for effects is real synchronization: connections, subscriptions, timers, imperative widgets, the browser APIs React doesn't model, and fetching when you aren't using a library.

Effect Events: reading the latest value without re-syncing React 19.2#

Sometimes an effect needs a value only to use it, not to decide when to re-run. The chat room shows a notification in the current theme when it connects. The theme is read inside the effect, so the linter wants it as a dependency, but then switching themes would reconnect to the room.

Before: theme change reconnects
useEffect(() => {
  const connection = createConnection(roomId);
  connection.on("connected", () => showNotification("Connected!", theme));
  connection.connect();
  return () => connection.disconnect();
}, [roomId, theme]); // the linter is right, and the behavior is wrong

useEffectEvent splits the non-reactive part out. The function it returns always sees the latest props and state, and it isn't a dependency:

useEffectEvent
import { useEffect, useEffectEvent, useState } from "react";
import { createConnection } from "./chat";

function ChatRoom({ roomId, theme }: { roomId: string; theme: string }) {
  const onConnected = useEffectEvent(() => {
    console.log(`notification: connected to #${roomId} (${theme} theme)`);
  });

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on("connected", () => onConnected());
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]); // theme isn't a dependency, and onConnected must not be one

  return <h3 style={{ color: theme === "dark" ? "#a8a29e" : "#292524" }}>#{roomId}</h3>;
}

export default function App() {
  const [roomId, setRoomId] = useState("general");
  const [dark, setDark] = useState(false);
  return (
    <>
      <select value={roomId} onChange={(e) => setRoomId(e.target.value)}>
        <option value="general">general</option>
        <option value="travel">travel</option>
      </select>{" "}
      <label>
        <input type="checkbox" checked={dark} onChange={(e) => setDark(e.target.checked)} /> Dark theme
      </label>
      <ChatRoom roomId={roomId} theme={dark ? "dark" : "light"} />
    </>
  );
}
Nothing logged yet.

Toggle the theme: no reconnect. Change the room: reconnect, and the notification uses whatever theme is current at that moment.

The rules, enforced by the linter:

  • Call the Effect Event only from inside effects (or other Effect Events) in the same component. Not during render, not from event handlers.
  • Don't pass it to other components or hooks, and don't put it in a dependency array. Its identity changes every render on purpose.
  • Don't use it to hide a dependency that should re-run the effect. It's for logic that's genuinely an event fired from inside the effect, like "connected" or "a message arrived".

Under the hood it fits the snapshot model: the effect keeps its old closure, and the Effect Event reaches into the latest render. React keeps the newest function in a hook slot and the wrapper you call always delegates to it, much like keeping the latest callback in a ref, but with rules the linter can check. (Calling it during render throws.)

useLayoutEffect: before the browser paints#

useEffect usually runs after the browser has painted. That's what you want almost always, because it doesn't delay the screen. The exception is when the effect measures layout and changes what's shown based on it, like a tooltip that has to decide whether to sit above or below its anchor. If that runs after the paint, the user sees one frame of the wrong position.

useLayoutEffect has the same API but runs synchronously after the DOM is updated and before the browser paints. State updates inside it are processed before paint too, so the user only ever sees the final position.

The demo makes the difference measurable. Each tooltip renders at the wrong spot first (over the button) and then measures itself and moves above. Rendering is slowed down so the wrong frame stays visible. A requestAnimationFrame scheduled at commit records whether the browser reached a frame before the measuring effect ran. Hover each button and read the console.

useEffect versus useLayoutEffect, measured
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { slowDown } from "guide-tools";

const boxStyle = (top: number | null) => ({
  position: "absolute" as const,
  left: 0,
  top: top ?? 0,
  padding: "6px 10px",
  borderRadius: 6,
  whiteSpace: "nowrap" as const,
  background: top === null ? "#f5d0c0" : "#292524",
  color: top === null ? "#292524" : "white",
});

function EffectTooltip() {
  const ref = useRef<HTMLDivElement>(null);
  const framePassed = useRef(false);
  const [top, setTop] = useState<number | null>(null);
  slowDown(40); // an expensive render

  useLayoutEffect(() => {
    const id = requestAnimationFrame(() => (framePassed.current = true));
    return () => cancelAnimationFrame(id);
  }, []);

  useEffect(() => {
    console.log("useEffect: did a frame run before measuring?", framePassed.current);
    setTop(-ref.current!.offsetHeight - 6);
  }, []);

  return <div ref={ref} style={boxStyle(top)}>Measured in useEffect</div>;
}

function LayoutTooltip() {
  const ref = useRef<HTMLDivElement>(null);
  const framePassed = useRef(false);
  const [top, setTop] = useState<number | null>(null);
  slowDown(40);

  useLayoutEffect(() => {
    const id = requestAnimationFrame(() => (framePassed.current = true));
    return () => cancelAnimationFrame(id);
  }, []);

  useLayoutEffect(() => {
    console.log("useLayoutEffect: did a frame run before measuring?", framePassed.current);
    setTop(-ref.current!.offsetHeight - 6);
  }, []);

  return <div ref={ref} style={boxStyle(top)}>Measured in useLayoutEffect</div>;
}

function HoverTarget({ label, tip }: { label: string; tip: ReactNode }) {
  const [hover, setHover] = useState(false);
  return (
    <span style={{ position: "relative", display: "inline-block", marginRight: 16 }}>
      <button onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}>
        {label}
      </button>
      {hover && tip}
    </span>
  );
}

export default function App() {
  return (
    <div style={{ paddingTop: 56 }}>
      <HoverTarget label="Hover: useEffect" tip={<EffectTooltip />} />
      <HoverTarget label="Hover: useLayoutEffect" tip={<LayoutTooltip />} />
    </div>
  );
}
Nothing logged yet.

The layout version always logs false and never shows the salmon box: it measured and moved before any frame. The useEffect version typically logs true and you can catch the salmon box over the button for a moment, because the browser painted between the commit and the effect. (Hover is a continuous event, so React schedules the effect normally. After discrete events like clicks, React flushes effects before the next paint, which can hide this bug in testing.)

Use useLayoutEffect only for measure-then-adjust work. It blocks painting, so slow code in it makes the whole app feel slow. It also doesn't run during server rendering, so server HTML shows the unmeasured state until hydration; that's another reason to keep it rare.

useInsertionEffect: for CSS-in-JS libraries#

useInsertionEffect runs during the commit, before any layout effects. It exists for one audience: CSS-in-JS libraries that generate <style> tags at runtime. Inserting styles before layout effects run means layout effects that read computed styles see the right ones, and the browser doesn't recalculate styles repeatedly.

Inside a CSS-in-JS library, not app code
import { useInsertionEffect } from "react";

const inserted = new Set<string>();

export function useCSS(rule: string) {
  useInsertionEffect(() => {
    if (!inserted.has(rule)) {
      inserted.add(rule);
      const style = document.createElement("style");
      style.textContent = rule;
      document.head.append(style);
    }
  });
}

It can't update state, and refs aren't attached yet when it runs. If you aren't writing a styling library, you won't need it. Knowing it exists and why is enough for an interview.

Pitfalls#

Check your understanding#

Quick checkHandler or effect?

Which of these belongs in an effect rather than an event handler?

Explain it out loudWhat is an effect for?

An interviewer asks: "Explain useEffect. Why does it run twice in development, and how do you avoid race conditions when fetching?"

Interview angle

Say it in 30 seconds

An effect synchronizes a component with something outside React: a connection, a subscription, a timer, a non-React widget. It runs after the commit and can return a cleanup; when its dependencies change, React runs the old cleanup and then the new setup, and on unmount it cleans up. Dependencies are every reactive value it reads, and the linter checks them. In development StrictMode runs setup, cleanup, setup to expose missing cleanups. Fetches need an ignore flag or AbortController against races. Many effects shouldn't exist: derive data during render, reset with keys, and put interaction logic in handlers.

What is useEffect for, and how should you think about it?

basic

Why does my effect run twice in development?

intermediate

What's the race condition when fetching in an effect, and how do you fix it?

intermediate

How do dependencies work, and what goes wrong if you leave one out?

intermediate

How do you decide between an event handler and an effect?

senior

Give examples of effects you'd remove in code review.

senior

What's the difference between useEffect, useLayoutEffect and useInsertionEffect?

senior

What problem does useEffectEvent solve?

senior

A parent and its child both have effects. In what order do they run, on mount and on update?

intermediate

Recap#

  • Effects synchronize components with external systems. Setup runs after commit; React runs the previous cleanup before every re-sync and on unmount. Think "start and stop syncing", not "mount and update".
  • Dependencies are every reactive value the effect reads, compared with Object.is. Fix unwanted re-runs by changing the code (move values inside, updater functions, Effect Events), never by lying to the linter.
  • StrictMode runs setup, cleanup, setup on mount in development to expose missing cleanups and prepare for remounting features. Fetching effects need an ignore flag or AbortController in the cleanup to avoid races.
  • Interactions go in handlers, display-driven synchronization goes in effects, and derived data, resets and notifications need no effect at all.
  • useEffectEvent (19.2) reads the latest values from inside an effect without making them dependencies. useLayoutEffect runs before paint for measure-then-adjust; useInsertionEffect is for CSS-in-JS libraries.

Sources#