Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

React useEffect: Dependencies, Cleanup and Common Mistakes

A component that renders correctly can still leak subscriptions or display data from an obsolete request. Effects connect a committed React tree to resources outside it. This guide focuses on ownership of those resources, dependency identity and cancellation rather than treating useEffect as a generic lifecycle callback.

Published Written by Reading time 8 min read
On this page Contents: quick navigation between sections

When does useEffect run?

import { useEffect } from "react";

export function DocumentTitle({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]);

  return null;
}

The first setup follows a committed render. When a dependency changes, React runs the previous cleanup, then the new setup; unmount runs the final cleanup. With no dependency array, setup runs after each commit of the component; with an empty array it has no reactive dependencies, not a global once-only guarantee. With [title], the example synchronizes the browser title on a change. It assumes a single owner of the title; route metadata is preferable when a framework manages it. Effects run only on the client. React may let the browser paint before an effect; do not assume exact paint timing. [1][2]

Dependencies, object identity and infinite loops

import { useEffect } from "react";

export function RoomSubscription({ roomId, subscribe }) {
  useEffect(() => {
    const unsubscribe = subscribe({ roomId });

    return () => {
      unsubscribe();
    };
  }, [roomId, subscribe]);

  return null;
}

React compares dependencies with Object.is, not deep equality. An object built during rendering is usually a new reference even when its fields match. Construct request or subscription options inside setup and declare their reactive inputs. Here subscribe is a prop and must be included; if its identity changes unnecessarily, fix the caller rather than omit it. A loop needs a state update plus a resulting dependency change. Inspect both and keep the exhaustive-deps rule enabled. [3][11]

Cleanup, timers and Strict Mode

import { useEffect, useState } from "react";

export function Timer({ intervalMs = 1000 }) {
  const [ticks, setTicks] = useState(0);

  useEffect(() => {
    const timerId = window.setInterval(() => {
      setTicks((previous) => previous + 1);
    }, intervalMs);

    return () => {
      window.clearInterval(timerId);
    };
  }, [intervalMs]);

  return <output>{ticks}</output>;
}

A resource belongs to the setup that created it. Clear that exact interval ID, unsubscribe the original listener and disconnect the original connection. A functional state updater reads the previous state without capturing ticks, so a tick does not restart the timer. If intervalMs changes, the previous timer is removed. Root Strict Mode adds a development-only setup/cleanup/setup stress test; suppressing it with a ref can conceal leaks. An empty array is not a license to skip cleanup. [4][6]

Fetching data without race conditions

import { useEffect, useState } from "react";

export function useProduct(productId) {
  const [result, setResult] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    let active = true;

    async function loadProduct() {
      try {
        const response = await fetch(
          `/api/products/${encodeURIComponent(productId)}`,
          { signal: controller.signal },
        );

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }

        const product = await response.json();

        if (active) {
          setResult({ productId, status: "success", product });
        }
      } catch (error) {
        if (active && !controller.signal.aborted) {
          setResult({ productId, status: "error", error });
        }
      }
    }

    void loadProduct();

    return () => {
      active = false;
      controller.abort();
    };
  }, [productId]);

  if (result?.productId !== productId) {
    return { status: "loading" };
  }

  return result;
}

A slow response for product A must not overwrite product B. Create a fresh AbortController for each setup, and mark that setup inactive on cleanup. fetch resolves on HTTP 404, so check response.ok before parsing. The hook returns loading for a different ID and ignores results after cleanup. This is a single-result example, not a cache or a runtime schema validator: validate JSON in production, define revalidation for repeated IDs, and prefer framework loaders or a query library when caching, SSR and request deduplication matter. Cancellation does not undo a server-side write. [6][7]

Derived values and user actions do not need effects

export function ProductSummary({ products, onCheckout }) {
  const total = products.reduce(
    (sum, product) => sum + product.priceInCents,
    0,
  );

  function handleCheckout() {
    onCheckout(products);
  }

  return (
    <button type="button" onClick={handleCheckout}>
      Checkout ({total} cents)
    </button>
  );
}

The total is determined by current props, so calculate it during rendering rather than storing a second value in state and synchronizing it later. Integer cents avoid ordinary decimal addition issues for this example; real payment totals belong on the server. Checkout is caused by a button press, so call it in the event handler. Moving it into an effect risks repeated submissions on remount. Use memoization for measured expensive calculations, not as a replacement for correct data ownership. [5]

Reading current values with useEffectEvent

import { useEffect, useEffectEvent } from "react";

export function Heartbeat({ intervalMs, onHeartbeat }) {
  const reportHeartbeat = useEffectEvent(() => {
    onHeartbeat(Date.now());
  });

  useEffect(() => {
    const timerId = window.setInterval(() => {
      reportHeartbeat();
    }, intervalMs);

    return () => {
      window.clearInterval(timerId);
    };
  }, [intervalMs]);

  return null;
}

A heartbeat has two distinct concerns: the interval duration determines when to recreate the timer, while the callback should observe current props. In React 19.2 or later, useEffectEvent separates the second concern. Call it from effect logic, keep it out of dependency arrays and do not use it to hide values that should trigger resynchronization. Older React projects can use a properly declared dependency or restructure their API. [8]

External stores, layout and diagnostics

import { useSyncExternalStore } from "react";

function subscribe(onStoreChange) {
  window.addEventListener("online", onStoreChange);
  window.addEventListener("offline", onStoreChange);

  return () => {
    window.removeEventListener("online", onStoreChange);
    window.removeEventListener("offline", onStoreChange);
  };
}

function getSnapshot() {
  return navigator.onLine;
}

function getServerSnapshot() {
  return true;
}

export function NetworkIndicator() {
  const online = useSyncExternalStore(
    subscribe,
    getSnapshot,
    getServerSnapshot,
  );

  return <output>{online ? "Online" : "Offline"}</output>;
}

A subscription that drives rendering from an external store is often better expressed using useSyncExternalStore. The example uses an optimistic server snapshot of true, reused during hydration; the actual browser value is read afterward. navigator.onLine is only a connectivity hint, not proof that an API works. Use useLayoutEffect for a necessary pre-paint measurement, not routine networking: it blocks paint. When debugging, trace setup and cleanup for each resource and inspect changes in dependency references rather than adding arbitrary delays. [9][10]

Correct effects express a reversible synchronization process. Keep render calculations and event-driven writes outside effects, declare actual dependencies, and design cleanup around the resource created by each setup. This makes remounts, changing inputs and slow networks ordinary cases rather than exceptional bugs.

React React Hooks useEffect Effect Dependencies Cleanup Strict Mode AbortController Race Conditions useEffectEvent useSyncExternalStore

Frequently asked questions

Why does useEffect run twice?

At the root, Strict Mode deliberately adds an extra setup and cleanup in development to expose missing teardown. It is not an extra production mount. [4]

Can the effect callback be async?

No. The callback must return nothing or a cleanup function, not a Promise. Put an async function inside setup and handle errors there. [1]

Does [] run only once?

It means there are no reactive dependencies. A remount creates a new setup, and Strict Mode can replay it in development. [1][4]

Why does an effect keep running?

Check whether an update inside the effect changes a dependency, including a newly allocated object or function. Do not silence the dependency lint. [3][11]

Sources and references

  1. React, useEffect↩1↩2↩3↩4↩5
  2. React, Lifecycle of Reactive Effects↩
  3. React, Removing Effect Dependencies↩1↩2↩3
  4. React, StrictMode↩1↩2↩3↩4↩5
  5. React, You Might Not Need an Effect↩
  6. React, Synchronizing with Effects↩1↩2
  7. MDN, Using the Fetch API↩
  8. React, useEffectEvent↩
  9. React, useLayoutEffect↩
  10. React, useSyncExternalStore↩
  11. React, exhaustive-deps↩1↩2↩3

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning