Skip to content
Visual explainer 4h to learn 4 steps

Effects & refs (and when not to use them)

Sync with external systems using useEffect and remove unnecessary effects.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 16 of 36

In short

useEffect runs code after React commits to the screen, to sync with systems outside React like timers, subscriptions or browser APIs. Many effects are unnecessary and can be replaced by computing values during render or handling events directly.

Explained simply

React components describe the screen. But sometimes you need to talk to things outside React: start a timer, connect to a chat server, listen for window resizes, or control a video player. useEffect is the tool for that.

An effect runs after React has updated the page. You tell it which values it depends on. When one of them changes, React first runs your cleanup, which undoes the old setup, and then runs the effect again with the new values.

Refs are a second tool. useRef gives you a box with a current field that keeps its value between renders, but changing it does not re-render the component. Use it for timer ids or to reach a real DOM element, for example to focus an input.

Effects are easy to overuse. If you only need to calculate something from props or state, do it during render. If something should happen because the user clicked, do it in the click handler. Fewer effects mean fewer bugs.

Press Play on a diagram to walk through it one step at a time.

CycleEffect lifecycle
  1. 1
    Render

    React computes the UI from props and state

  2. 2
    Commit

    React updates the DOM

  3. 3
    Run effect

    Connect to the external system

  4. 4
    Dependencies change

    React re-renders with new values

  5. 5
    Cleanup

    Disconnect the old setup before running again

  6. Back to step 1
SequenceroomId changes from "general" to "music"
Component
React
Chat server
  1. 1effect: connect("general")
    React to Chat server: effect: connect("general")
  2. 2re-render with roomId "music"
    Component to React: re-render with roomId "music"
  3. 3cleanup: disconnect("general")
    React to Chat server: cleanup: disconnect("general")
  4. 4effect: connect("music")
    React to Chat server: effect: connect("music")
  5. 5unmount
    Component to React: unmount
  6. 6cleanup: disconnect("music")
    React to Chat server: cleanup: disconnect("music")

In depth

When an effect actually runs

React renders your component, commits the changes to the DOM, lets the browser paint, and then runs useEffect callbacks. Because they run after paint, effects never block the user from seeing the update. Effects do not run during server rendering at all, which is why browser-only code like window or localStorage belongs in an effect or an event handler.

useLayoutEffect runs after the DOM update but before paint. Use it only when you must measure layout, such as a tooltip's size, and adjust it before the user sees a flicker; it blocks painting, so keep it short. With an empty dependency array, an effect runs once after mount. With no array at all, it runs after every render, which is rarely what you want.

FlowOne render with an effect
  1. 1
    Render

    Your function runs and returns JSX

  2. 2
    Commit

    React updates the DOM

  3. 3
    useLayoutEffect

    Runs before paint; can measure layout

  4. 4
    Browser paints

    The user sees the new screen

  5. 5
    useEffect

    Cleanup of the old effect, then the new one

Dependencies are not a choice

The dependency array is not a list of when you want the effect to run. It must contain every reactive value the effect reads: props, state, and anything calculated from them. React compares each item with Object.is. The eslint rule react-hooks/exhaustive-deps checks this for you; do not silence it.

Objects and functions created during render are new on every render, so listing them makes the effect run every time. Move them inside the effect, or move them outside the component if they do not use props or state. When an effect must read a value without reacting to it, such as the current theme when logging a page view, React 19.2 adds useEffectEvent: wrap that logic in an effect event and call it from the effect; it always sees the latest values and does not belong in the array.

  • Every prop or state read inside goes in the array
  • Move helper objects and functions inside the effect
  • Use the updater form of a setter to drop state from deps
  • useEffectEvent for non-reactive logic (React 19.2+)

Cleanup, Strict Mode and race conditions

Every effect that starts something should stop it: clearInterval for timers, removeEventListener for listeners, disconnect for sockets. In development, Strict Mode mounts each component, immediately unmounts it, and mounts it again. A correct effect with cleanup behaves the same; a missing cleanup shows up as two connections or doubled events. This only happens in development.

Fetching in an effect has a classic race. If userId changes from 1 to 2 quickly, the response for 1 may arrive last and overwrite user 2. Fix it in cleanup: abort the request with an AbortController, or set an ignore flag that the old request checks before calling setState. In real apps, prefer a data library such as TanStack Query, or server components in Next.js, which handle caching and races for you.

You might not need an effect

Many effects copy data from one place to another and cause an extra render each time. Common cases have simpler fixes. Derived data: compute it in render (const visible = todos.filter(...)), with useMemo if it is truly expensive. Resetting state when a prop changes: render the component with a key. Reacting to a user action, like sending analytics after Buy: do it in the event handler, because you know exactly why it happened there.

A good test is to ask why this code runs. If the answer is because the component was displayed, an effect fits. If the answer is because the user did something, it belongs in a handler.

CompareEffect vs better place
With an effect (avoid)
  • Effect sets fullName from first and last
  • Effect resets the form when userId changes
  • Effect posts to /api/buy when bought is true
  • Effect copies a prop into state
Without (prefer)
  • const fullName = first + " " + last
  • Render the form with key={userId}
  • Call the API in the Buy click handler
  • Read the prop directly

Refs: memory without re-rendering

useRef returns the same object on every render. Changing ref.current does not re-render, which makes it right for values the UI does not show: a timer id, the previous value of a prop, or a flag like hasShownToast. Do not read or write ref.current during rendering, except for lazy setup; the screen would not stay in sync with it. Use refs in handlers and effects.

For DOM nodes, pass the ref to an element and React sets ref.current after commit, so it is null during the first render. Use it to focus, scroll into view, measure size, or call play() on a video. In React 19, a ref callback can return a cleanup function, which React calls when the element is removed.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Sync with an external system using useEffect~1h
  2. 2
    Write cleanup functions~1h
  3. 3
    Store mutable values and DOM nodes with useRef~1h
  4. 4
    Remove effects you do not need~1h

Key points

  • Effects are for syncing with external systems, not for transforming data.
  • List every reactive value the effect uses in its dependency array.
  • Return a cleanup function to undo subscriptions, timers and listeners.
  • useRef stores a mutable value or DOM node without causing re-renders.
  • In development Strict Mode, effects run twice to expose missing cleanup.

Key terms

Tap a card to flip it. 0/5 known

Examples

tsx
function Clock() {
  const [now, setNow] = useState(new Date());

  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(id); // cleanup
  }, []);

  return <p>{now.toLocaleTimeString()}</p>;
}

function SearchBox() {
  const inputRef = useRef<HTMLInputElement>(null);
  return <input ref={inputRef} onFocus={() => inputRef.current?.select()} />;
}

An interval with cleanup, and a ref to a DOM node.

Fetching a profile without race conditions

Step 1: the effect depends on userId, so it reruns when the user changes. Step 2: create an AbortController and pass its signal to fetch. Step 3: in cleanup, abort. If userId changes before the old response arrives, the old request is cancelled and can never overwrite the new data. Step 4: ignore the AbortError, because it is expected.

tsx
import { useEffect, useState } from "react";

type User = { id: string; name: string };

export function Profile({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null);
  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((res) => res.json())
      .then((data: User) => setUser(data))
      .catch((err) => { if (err.name !== "AbortError") console.error(err); });
    return () => controller.abort();
  }, [userId]);
  return <h1>{user ? user.name : "Loading..."}</h1>;
}

Deleting an effect that caused double renders

The original code kept a filtered list in state and updated it in an effect whenever todos or filter changed. That costs an extra render each time and shows one frame of stale data. Step 1: delete the visibleTodos state. Step 2: delete the effect. Step 3: compute the list during render. Same result, less code, no stale frame.

tsx
type Todo = { id: string; text: string; done: boolean };

// Before:
// const [visible, setVisible] = useState<Todo[]>([]);
// useEffect(() => { setVisible(todos.filter(...)); }, [todos, filter]);

// After:
export function TodoList({ todos, filter }: { todos: Todo[]; filter: "all" | "open" }) {
  const visible = filter === "open" ? todos.filter((t) => !t.done) : todos;
  return <ul>{visible.map((t) => <li key={t.id}>{t.text}</li>)}</ul>;
}

Quick reference

  • useEffect runs after paint; useLayoutEffect runs before paint (measure layout only)
  • No deps array: every render. []: after mount. [a, b]: when a or b changes
  • Return a cleanup function for every timer, listener, socket or subscription
  • Strict Mode mounts, unmounts and remounts in development to test your cleanup
  • Abort stale fetches in cleanup with AbortController
  • Derived data goes in render; user-caused work goes in event handlers
  • ref.current changes do not re-render; do not read it during render
  • React 19.2: useEffectEvent reads latest values without adding them to deps

Common mistakes

  • Using an effect to copy props into state instead of deriving the value.
  • Omitting dependencies, which leaves the effect using stale values.
  • Forgetting cleanup, causing duplicate listeners or memory leaks.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An effect has the dependency array [roomId]. roomId changes. What happens, in order?

Question 2

2In development your WebSocket connects twice on page load. What is the most likely cause?

Question 3

3You need fullName from firstName and lastName state. What should you do?

Question 4

4Why is inputRef.current null during the first render?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Show the window width in a component and keep it updated when the window is resized. Clean up the listener.

  2. Exercise 2medium

    Build a Stopwatch with Start, Stop and Reset. Store the interval id in a ref so you can stop it, and make sure unmounting stops the timer.

  3. Exercise 3hard

    Search results load in an effect whenever query changes. Typing "rea" then "react" sometimes shows results for "rea". Fix it with an ignore flag (no AbortController).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does useEffect run twice in development?
React Strict Mode mounts, unmounts and remounts components in development to check that your effects clean up correctly. It does not happen in production builds.
Should I fetch data in useEffect?
It works for simple cases if you handle races and loading states. For real apps, prefer a data library like TanStack Query or, in Next.js, fetching in server components.
What is the difference between useRef and useState?
Both keep values between renders, but only changing state triggers a re-render. Use a ref for values the screen does not show.
Can I make the effect callback async?
Not directly, because an async function returns a promise and React expects a cleanup function or nothing. Define an async function inside the effect and call it.

Go deeper

ShareXLinkedInWhatsApp