Skip to the content

Lesson 166 of 296

useEffect

What you will learn

  • What effects are for
  • The dependency array
  • Clean-up functions
  • Fetching data in an effect, and race conditions
  • The most common useEffect bugs
  • When you do NOT need an effect
  • useEffectEvent
On this page

What is an effect?

Rendering must be pure (Lesson 163). But components sometimes need to synchronise with something outside React: a timer, a subscription, a browser API, the page title, a network connection. useEffect runs code after React has committed the render to the screen.

TSX
import { useEffect } from "react";

function PageTitle({ title }: { title: string }) {
  useEffect(() => {
    document.title = title;
  }, [title]);
  return <h1>{title}</h1>;
}

The dependency array

The second argument decides when the effect runs:

Dependency arrayEffect runs
[title]After the first render, and after any render where title changed
[]Only after the first render (on mount)
MissingAfter every render

Every value from the component (props, state, functions defined in the component) that the effect uses must be in the array. Otherwise the effect uses stale values (Lesson 170). The ESLint rule react-hooks/exhaustive-deps checks this for you. Do not silence it.

React compares dependencies with Object.is. Objects, arrays and functions created during render are new every time, so they make the effect run after every render.

Clean-up

An effect can return a function that undoes it. React runs the clean-up before the effect runs again and when the component unmounts (is removed).

TSX
function Clock() {
  const [now, setNow] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  return <time>{now.toLocaleTimeString("en-GB")}</time>;
}

Without the clean-up, every mount would start another interval that never stops: a memory leak, and in StrictMode development you would see two intervals.

Things that need clean-up: timers, event listeners, subscriptions, WebSocket connections, observers, and in-flight requests.

Fetching data in an effect

TSX
type UserData = { id: number; name: string };

function UserProfile({ userId }: { userId: number }) {
  const [user, setUser] = useState<UserData | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    setUser(null);
    setError(null);

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json() as Promise<UserData>;
      })
      .then(setUser)
      .catch((err: unknown) => {
        if (err instanceof Error && err.name !== "AbortError") setError(err.message);
      });

    return () => controller.abort();
  }, [userId]);

  if (error) return <p role="alert">{error}</p>;
  if (!user) return <p>Loading...</p>;
  return <h2>{user.name}</h2>;
}

The race condition: the user switches from profile 1 to profile 2 quickly. If the response for 1 arrives after the response for 2, the page shows the wrong person (the same problem as Lesson 89). The clean-up aborts the old request whenever userId changes, so only the latest response is used.

In real apps, fetching in effects means writing loading, error, caching and retry logic yourself, every time. Most teams use a data-fetching library (TanStack Query, SWR) or server components in Next.js (Part 13) instead. Know how to do it in an effect, and know why teams usually do not.

Common useEffect bugs

BugCauseFix
Infinite loopThe effect sets state that is in its own dependency list, or depends on an object created every renderRemove unnecessary state; move objects inside the effect or memoise them
Stale valuesA dependency is missingAdd it (follow the lint rule); use functional updates
Memory leak / duplicated listenersNo clean-upReturn a clean-up function
Wrong data shownRace condition in fetchAbort or ignore stale responses in the clean-up
async directly as the effectuseEffect(async () => ...) returns a promise, not a clean-upDefine an async function inside the effect and call it

You might not need an effect

Effects are for external systems. Many effects in real code are unnecessary, which makes code slower and buggier. Common cases:

Instead of an effect that...Do this
Calculates a value from props or state and stores it in stateCalculate it during render: const fullName = first + " " + last; (use useMemo if it is expensive)
Responds to a user event (submit, click)Put the logic in the event handler
Resets state when a prop changesUse a key to reset the component (Lesson 162)
Notifies the parent of a changeCall the parent's callback in the event handler
Fetches dataA data library or server components

This is a popular senior-level interview topic. The React documentation has a full page called "You Might Not Need an Effect".

useEffect vs useLayoutEffect

useLayoutEffect runs after the DOM is updated but before the browser paints. Use it only to measure the layout and adjust it without a visible flicker (for example, positioning a tooltip). It blocks painting, so prefer useEffect otherwise.

useEffectEvent (React 19.2)

Sometimes an effect needs to read the latest value of something without re-running when it changes. For example, a chat connection should reconnect when the room changes, but not when the theme changes, even though the "connected" notification uses the theme. React 19.2 added useEffectEvent: a function defined with it always sees the latest props and state, and it is not a dependency.

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

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

Only call effect events from inside effects.

How to say it in an interview

"useEffect synchronises a component with external systems after the render is committed. The dependency array must include every reactive value the effect uses, otherwise it reads stale values; objects and functions created during render change every time. I return a clean-up function for timers, listeners, subscriptions and in-flight requests, and when fetching I abort in the clean-up to avoid race conditions, although in real apps I prefer a data library or server components. Many effects are unnecessary: derived values belong in render, user actions in event handlers, and resets can use a key. useEffectEvent lets an effect read the latest values without re-running."

Key words

WordMeaning
EffectCode that synchronises a component with something outside React
Dependency arrayThe values that decide when an effect re-runs
Clean-upA function that undoes an effect
UnmountRemoving a component from the page
Race conditionResponses arriving in an unexpected order
useLayoutEffectAn effect that runs before the browser paints
useEffectEventEffect logic that reads the latest values without being a dependency

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.