Skip to content
FrontDepth, Home

React & Rendering

useEffect: dependencies and cleanup

How useEffect synchronises a component with systems outside React — when setup and cleanup run, how dependencies are compared, why Strict Mode runs effects twice — and how to avoid render loops, stale closures, fetch races and needless effects.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Junior level.

JuniorConcept

What an Effect is for

A React component has two kinds of logic. Rendering turns props and state into JSX and must be pure: same inputs, same output, no side effects. Event handlers run in response to a specific interaction — a click, a submit — and are where things may change. Some work fits neither: it must happen because the component is on the screen, not because the user did something. That is what an Effect is for. react.dev defines Effects as side effects that are "caused by rendering itself, rather than by a particular event".

The typical job of an Effect is to synchronise with an external system, something React does not control:

  • a network connection (a chat room, a WebSocket);
  • browser APIs: document.title, an IntersectionObserver, a listener on window;
  • timers;
  • a non-React widget: a map, a chart, a video player.
JSX
import { useEffect, useState } from "react";

function ChatRoom({ roomId }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on("message", (m) => setMessages((list) => [...list, m]));
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);

  return <MessageList messages={messages} />;
}

The Effect has three parts: the setup (connect), the cleanup — the function the setup returns (disconnect) — and the dependencies ([roomId]: reconnect when the room changes). Read it as a description of how to start and how to stop one synchronisation, not as "code that runs on mount". react.dev puts it this way: an Effect can only start synchronising something and later stop synchronising it.

What does not belong in an Effect

  • Calculations. If a value can be computed from props and state, compute it while rendering.
  • Reactions to user actions. Submitting a form, buying a product, showing a toast after a click: these belong in the event handler that caused them.

react.dev's rule of thumb is to ask why the code runs. If it runs because of a particular interaction, it is an event. If it runs because the user sees the component, it is an Effect.

Effects run only on the client, never during server rendering. That also makes them the place for code that needs browser-only APIs.

JuniorConcept

When effects and cleanups run

React works in two steps: render (call your component and compute the JSX) and commit (apply the changes to the DOM). Effects run after the commit:

Text
render → commit (DOM updated) → browser paints → useEffect setup

If the update was not caused by an interaction, React generally lets the browser paint first and runs the Effect afterwards, so effects don't delay what the user sees. If it was caused by an interaction such as a click, React may run the Effect before the paint. Either way, the DOM is already up to date when the Effect runs.

Cleanup timing

After every commit in which the dependencies changed, React first runs the previous cleanup with the old values, then the new setup with the new values. When the component is removed, the last cleanup runs one final time:

Text
mount, roomId "general"       setup:   connect "general"
re-render, same roomId        (nothing)
re-render, roomId "travel"    cleanup: disconnect "general"
                              setup:   connect "travel"
unmount                       cleanup: disconnect "travel"

Each render has its own Effect. The cleanup that runs was created during the earlier render, so it is a over that render's roomId — which is exactly what you want: you disconnect from the room you connected to. Inside one component, effects run in the order they are declared, and a child's effects run before its parent's.

Strict Mode: setup, cleanup, setup

In development, Strict Mode runs one extra setup + cleanup cycle right after the first mount, so you see connect → disconnect → connect. It is a stress test. If the cleanup mirrors the setup, the user can't tell the difference. If something breaks — two connections, a listener registered twice, a timer firing twice — the cleanup is missing or incomplete. In production the setup runs once.

The right question is not "how do I run an Effect once?" but "how do I make my Effect work after remounting?". Don't hide the extra cycle with a ref flag: react.dev warns that this hides the bug instead of fixing it, and the same unmount and remount happens for real when the user leaves a screen and comes back.

JuniorConcept

The dependency array

JSX
useEffect(setup);
useEffect(setup, []);
useEffect(setup, [a, b]);
  • No array: the Effect runs after every commit.
  • []: it runs after the first commit only, and its cleanup on unmount. That is correct only if the Effect really reads no reactive values.
  • [a, b]: after the first commit and after every commit in which a or b changed.

"Changed" means that Object.is returned false when comparing a dependency with its value from the previous render. For strings, numbers and booleans that is ordinary value equality (with two quirks: NaN equals NaN, and 0 differs from -0). For objects, arrays and functions it is identity: a new object with the same contents counts as changed.

JSX
function SearchResults({ query, page }) {
  const options = { query, page };

  useEffect(() => {
    loadResults(options);
  }, [options]);
}

options is a new object on every render, so this Effect runs after every render. Depend on the primitives instead ([query, page]) and create the object inside the Effect.

Dependencies are not a choice

The array must list every reactive value the Effect reads: props, state, and everything declared in the component body that is computed from them. The react-hooks/exhaustive-deps lint rule checks this for you.

  • The set function from useState and the ref object from useRef are stable, so you may leave them out.
  • Values declared outside the component are not reactive and are not listed.
  • Mutable values such as ref.current or location.pathname can't be dependencies: changing them doesn't cause a render, so React would never notice.

If the linter asks for a dependency you don't want, don't suppress the warning — change the code so the Effect doesn't need the value. Move it inside the Effect or outside the component, use an updater function (setCount((c) => c + 1)) instead of reading the state, or read the value through an Effect Event. A suppressed lint warning is how most stale-closure bugs start.

MiddleConcept

You might not need an Effect

If no external system is involved, you probably don't need an Effect. Effects that only adjust state based on other state make a component slower — an extra render after each commit — and harder to follow. The most common cases react.dev lists:

Derived values: compute them during rendering.

JSX
const [fullName, setFullName] = useState("");
useEffect(() => {
  setFullName(firstName + " " + lastName);
}, [firstName, lastName]);

The first render shows an outdated fullName, then the Effect sets state and React renders again. const fullName = firstName + " " + lastName; is shorter, always consistent, and renders once. If the calculation is expensive, wrap it in useMemo, not in an Effect.

Resetting state when a prop changes: use a key. <Profile key={userId} userId={userId} /> makes React treat each user's profile as a separate component, so its state resets without an Effect that "clears" it.

Reacting to user actions: use the event handler.

JSX
function BuyButton({ product }) {
  function handleClick() {
    addToCart(product);
    showNotification(`Added ${product.name} to the cart`);
  }
  return <button onClick={handleClick}>Buy</button>;
}

An Effect that watches the cart and shows the notification would also fire on page load, after a refresh, or when the cart changes for some other reason. The notification is caused by the click, so it belongs in the click handler.

Chains of Effects that set state only to trigger other Effects: compute what you can during rendering and set all the next state in one event handler.

Notifying a parent about a change: call the parent's callback in the same event handler that updates the state, or lift the state up so there is nothing to keep in sync.

Subscribing to an external store: useSyncExternalStore is the purpose-built hook.

What remains are real synchronisations: connections, subscriptions, timers, imperative widgets, analytics for "the user saw this screen", and data fetching (with the caveats in the fetching section). When you review a component, removing an unnecessary Effect is often the fix for its bug.

MiddlePitfalls

Infinite render loops

An Effect that sets state causes a re-render. Once, that is fine. It turns into a loop when the re-render also changes the Effect's dependencies — or when there is no dependency array at all:

JSX
useEffect(() => {
  setCount(count + 1);
});

react.dev compares this to plugging a power outlet into itself: the Effect sets state, the render runs the Effect again, the Effect sets state again.

A less obvious version: a product list filters its items in an Effect, and the filter object is created during rendering:

JSX
function ProductList({ products, status, sort }) {
  const [visible, setVisible] = useState([]);
  const filter = { status, sort };

  useEffect(() => {
    setVisible(applyFilter(products, filter));
  }, [products, filter]);

  return <Table rows={visible} />;
}

Every render creates a new filter object, so Object.is reports a changed dependency. The Effect runs and stores a new array in visible; that state change causes a render, which creates another filter. The page keeps committing while it should be idle. In development React logs "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render." The production build logs nothing — the page just burns CPU.

A loop needs two things: the Effect updates state, and that update changes the Effect's dependencies. Break either:

  1. Don't use an Effect. visible is derived data: const visible = applyFilter(products, { status, sort }); during rendering, inside useMemo if it is expensive. This removes the extra render entirely.
  2. Depend on primitives. List [products, status, sort] and build the object inside the Effect.
  3. Stabilise the object with useMemo(() => ({ status, sort }), [status, sort]) when it really has to be passed around.

Setting state to the same value (by Object.is) lets React bail out, which is why setReady(true) in a loop-shaped Effect stops after one round while setVisible([...]) never does. Watch for the same trap with functions and arrays created in render, and with props that a parent recreates on every render.

MiddlePitfalls

Stale closures in Effects

Every render creates new props and state constants, and an Effect created in that render is a over them. If the Effect leaves a function running after newer renders — an interval, a subscription callback — that function keeps seeing the old values. That is a .

Take an editor that saves the draft every few seconds:

JSX
function Editor({ docId }) {
  const [text, setText] = useState("");

  useEffect(() => {
    const id = setInterval(() => {
      saveDraft(docId, text);
    }, 3000);
    return () => clearInterval(id);
  }, []);

  return <textarea value={text} onChange={(e) => setText(e.target.value)} />;
}

The Effect runs once, so its interval callback belongs to the first render, where text is "". The user types and sees the new text, while every three seconds the app saves the empty first version. After a reload the edits are gone. The linter would have reported docId and text as missing dependencies: [] here is a suppression in disguise.

Fixes, from the most direct:

  1. List the dependencies: [docId, text]. The interval is recreated with a fresh closure after each change, and there is still only one timer at a time. For autosave this also means "save three seconds after the last keystroke", a — a setTimeout expresses that more clearly than an interval.
  2. Read the latest value from a ref. A ref is one mutable box shared by all renders:
JSX
const textRef = useRef(text);
useEffect(() => {
  textRef.current = text;
}, [text]);

useEffect(() => {
  const id = setInterval(() => saveDraft(docId, textRef.current), 3000);
  return () => clearInterval(id);
}, [docId]);

Update the ref in an Effect or an event handler, not during rendering.

  1. useEffectEvent (stable since React 19.2): put "save the current text" in an Effect Event, which always sees the latest props and state without being a dependency. See the senior section below.

An updater function (setCount((c) => c + 1)) fixes a stale closure only when the callback needs to write state based on its previous value. Autosave needs to read the current value and send it somewhere else, so it needs one of the fixes above.

SeniorExample

Data fetching and race conditions

Fetching in an Effect is allowed, but the naive version has a classic bug — responses can arrive in a different order than the requests were sent:

JSX
useEffect(() => {
  fetchResults(query).then((json) => setResults(json));
}, [query]);

Type "re", then "react": two requests go out. If the "re" response is slower, it arrives last and overwrites the results for "react", and the screen shows results for a query the user no longer has.

The fix react.dev shows is a cleanup that marks the old request as stale:

JSX
useEffect(() => {
  let ignore = false;
  fetchResults(query).then((json) => {
    if (!ignore) setResults(json);
  });
  return () => {
    ignore = true;
  };
}, [query]);

When query changes, React runs the previous cleanup before the next setup, so the previous Effect's ignore becomes true and its late response is dropped. Each Effect has its own ignore — the cleanup is a closure over its render's variable — so only the latest query's response is used.

You can also cancel the request itself:

JSX
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
    .then((response) => response.json())
    .then((json) => setResults(json))
    .catch((error) => {
      if (error.name !== "AbortError") setError(error);
    });
  return () => controller.abort();
}, [query]);

Aborting also saves bandwidth; an aborted fetch rejects with an AbortError, which you ignore. In development, Strict Mode starts the first request and aborts it immediately — expected, since production sends one request.

Why a data layer does this better

A fetch in an Effect doesn't cache, doesn't deduplicate requests between components, starts only after rendering (so nested components fetch in a waterfall) and doesn't run on the server. react.dev recommends the built-in data fetching of a framework, or a client-side cache such as TanStack Query, SWR or React Router. The ignore pattern still matters: it is what those tools do for you, and it is a standard interview question.

SeniorFramework

useLayoutEffect and useEffectEvent

useLayoutEffect

useLayoutEffect has the same signature as useEffect, but it fires before the browser repaints. React guarantees that its code, and any state update scheduled from it, is processed before the paint. That makes it the tool for measuring layout and correcting it before the user sees the wrong version:

JSX
function Tooltip({ anchorTop, children }) {
  const ref = useRef(null);
  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    setHeight(ref.current.getBoundingClientRect().height);
  }, []);

  const top = anchorTop - height < 0 ? anchorTop + 24 : anchorTop - height;
  return <div ref={ref} style={{ position: "absolute", top }}>{children}</div>;
}

With useEffect the browser could paint the tooltip in the wrong place and move it a frame later: a visible flicker. The price is that layout effects block painting, and a state update inside one makes React run all remaining Effects immediately, useEffect ones included. Prefer useEffect, and reach for useLayoutEffect only when a measurement has to be applied before paint. Layout effects don't run during server rendering either, so the server HTML is always the first, unmeasured pass.

useEffectEvent

Sometimes an Effect must read a value without reacting to it. A chat room should reconnect when roomId changes, but not when theme changes, even though the "connected" notification uses theme:

JSX
import { useEffect, useEffectEvent } from "react";

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showNotification("Connected!", theme);
  });

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.on("connected", () => onConnected());
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]);
}

An Effect Event always sees the latest props and state, and it is not reactive, so it never goes into the dependency array. useEffectEvent shipped as a stable API in React 19.2 (the current release is 19.3); update eslint-plugin-react-hooks so the linter does not ask for it as a dependency. The rules:

  • call it only from inside Effects (or other Effect Events) of the same component, never during rendering;
  • don't pass it to other components or hooks — its identity changes on every render, by design;
  • don't use it to hide dependencies that should re-run the Effect. It is for logic that is conceptually an event fired from an Effect: logging a visit with the current cart size, a notification in the current theme, an autosave tick that reads the latest text.
SeniorInterview tips

Interview tips

A 30-second answer. "useEffect synchronises a component with something outside React. React runs the setup after the commit, usually after paint. When a dependency changes — compared with Object.is — it runs the previous cleanup with the old values and then the new setup, and the last cleanup runs on unmount. In development Strict Mode adds one setup + cleanup cycle to check that the cleanup undoes the setup. Most bugs are missing cleanups, unstable dependencies and stale closures — and many Effects shouldn't exist at all."

Questions you are likely to get

  • What is the order of render, commit, effect and cleanup? Draw the timeline for mount → update → unmount, and point out that the cleanup sees the old render's values.
  • Why does my Effect run twice in development? Strict Mode. Fix the cleanup; don't add a ref flag.
  • Why is this component stuck in a loop? The Effect sets state and depends on an object, array or function recreated every render — or has no array. Derive during rendering, depend on primitives, or memoise.
  • Why does my interval see old state? A stale closure. Fixes: an updater function, correct dependencies, a ref, useEffectEvent.
  • How do you fetch safely in an Effect? An ignore flag or AbortController in the cleanup; better still, a framework loader or a cache library.
  • useEffect or useLayoutEffect? Usually after paint vs before paint. Layout effects block painting; use them for measurements.

Mistakes that cost points

  • Explaining effects as componentDidMount / componentDidUpdate. Talk about starting and stopping synchronisation; react.dev advises thinking from the Effect's perspective, one start/stop cycle at a time.
  • Treating [] as a way to say "run once". An empty array is the result of an Effect that reads no reactive values, not a goal.
  • Suppressing exhaustive-deps instead of restructuring the code.
  • Using an Effect to compute derived state or to respond to a click.

Senior signal

Show judgement, not just rules: which Effects you would delete in a code review, how you would wrap an Effect in a custom hook (useOnlineStatus, useChatRoom) so components get a clear API, and when the work belongs to the framework's data layer instead of an Effect. Tie it to real failures: the render loop that only shows in development logs, the autosave that silently saved stale text, the search that showed results for an old query.

The platform's render-loop, autosave-stale-closure and search-race incidents let you practise debugging Effects in a running app.

JuniorReview checklist

What to check when reviewing Effects

Use this list when you review an Effect you did not write: a teammate's, a library's or an AI assistant's. Effect bugs rarely show at once; they surface later as duplicate connections, render loops and callbacks reading old values.

  • Does the Effect synchronise with something outside React? Values computed from props or state belong in render, reactions to a click or submit in the event handler. An Effect that only sets state from other state adds a render with stale data; often the fix is to delete it.
  • Does every setup have a cleanup that undoes it? Connections are closed, timers cleared, listeners removed with the same function reference. In development Strict Mode runs setup, cleanup, setup on mount: a duplicate connection or a timer firing twice means a missing cleanup; a ref flag skipping the second run only hides it.
  • Does the dependency array list every reactive value the Effect reads? Props, state and values computed from them all count; a suppressed react-hooks/exhaustive-deps warning or a [] that omits them leaves intervals and subscriptions reading an old render's values, a .
  • Does an Effect that sets state depend on an object, array or function created during render? Each render brings a new reference that Object.is treats as changed, so an Effect storing a new object or array each time never stops, like one with no array. Development logs "Maximum update depth exceeded", production nothing; depend on primitives instead.
  • When a fetch's input changes, is the old response ignored or aborted? Responses can arrive out of order: without an ignore flag or an AbortController aborted in the cleanup, a slow older response overwrites the newer one.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    4 predict-output · 3 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions

Hands-on work that uses this topic.