Thuta Learning
React
IntermediateWeb DevelopmentIntermediate

useEffect Hook

ReactLesson 1235 min

What you'll walk away with

  • Explain that an effect runs after the render has been committed to the screen
  • Tell apart no dependency array, [] and [a, b], and list every value the effect uses
  • Write cleanup functions for intervals, event listeners and connections
  • Understand Strict Mode's setup → cleanup → setup in development, and compute derived values during render instead of in an effect

Explain it simply

Explain it simply

A component's main job is to describe UI. Sometimes, though, once that UI is on the screen, it also has to connect with the world outside React: change the browser tab's title, start a timer, connect to a chat server.

useEffect is for that work. Think of a light switch: switch it on when you enter a room (mount) and off when you leave (unmount). The effect is the "on", and the cleanup function the effect returns is the "off".

Problem → Why → Solution

The problem: the clock counts two per second

Run the Clock below in development and seconds jumps by two every second instead of one. Worse, when the user navigates away and Clock disappears, the interval keeps running in the background, updating state nobody can see.

Clock.jsx
import { useEffect, useState } from 'react';

function Clock() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    setInterval(() => {
      setSeconds((s) => s + 1);
    }, 1000);
    // no cleanup: nothing ever stops this interval
  }, []);

  return <p>Running for {seconds}s</p>;
}

Why is it doubled?

In development, Strict Mode simulates an extra unmount and mount right after mounting, so the effect runs setup → cleanup → setup. With no cleanup, the first interval is never stopped and two intervals run side by side. Adding return () => clearInterval(id); leaves exactly one interval in development and in production, and stops it on unmount.

Core concept: effects synchronize with something outside React

Rendering must stay pure: compute JSX from props and state, without starting timers or sending requests. useEffect(setup, dependencies) runs the setup function after React has committed the render to the screen. By then the DOM is ready, and the effect can connect to systems React does not control, such as browser APIs, timers, the network or a third-party widget. An effect runs not because of a particular event, but because "while this component is on screen, it must stay in sync with that system".

The dependency array says when the effect should run again. With no array, it runs after every render. With [], it runs once after mount. With [roomId, userId], it runs on mount and whenever one of those values changes, compared with Object.is. Crucially, you do not choose dependencies: every prop, piece of state, and variable or function declared in the component that the effect reads must be listed. The exhaustive-deps rule of eslint-plugin-react-hooks points out any you missed. To remove a dependency, change the code so the effect no longer needs that value.

The setup function may return a cleanup function. Before re-running the effect because a dependency changed, React runs the cleanup with the old values, and it runs it once more when the component unmounts. Write them as pairs: connect/disconnect, addEventListener/removeEventListener, setInterval/clearInterval.

In development, <StrictMode> deliberately runs setup → cleanup → setup right after mounting. If your cleanup is correct, the user cannot tell the difference; if they can, the cleanup has a bug. Production does not do this extra run.

Mental model: setup, cleanup, repeat
  1. Render is committed to the screen
  2. Setup runs (connect / subscribe)
  3. Deps change: cleanup, then setup
  4. Unmount: cleanup one last time

Every setup must be undoable by its cleanup.

General pattern

jsx
useEffect(() => {
  const handle = connectTo(externalSystem, value);   // setup
  return () => {
    disconnect(handle);                               // cleanup
  };
}, [value]);   // every reactive value used above

// useEffect(fn)      -> after every render
// useEffect(fn, [])  -> after mount only (cleanup on unmount)

Setup connects to the system and cleanup disconnects. Every reactive value used in the effect goes in the dependency array. Without an array the effect runs after every render; with [] it runs only after mount.

Example: keeping the tab title in sync with a count

The browser tab's title, document.title, lives outside the JSX that React manages, so an effect keeps it in sync with the count state. The effect only overwrites the title and leaves nothing running, so it needs no cleanup.

jsx
import { useEffect, useState } from 'react';

function TitleChanger() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = 'You clicked ' + count + ' times';
  }, [count]);

  return (
    <button onClick={() => setCount(count + 1)}>
      Click to change title ({count})
    </button>
  );
}

Code breakdown

  1. Line 4const [count, setCount] = useState(0);

    count is the single source of truth for both the button and the title; the title is not stored as separate state.

  2. Line 6useEffect(() => {

    This function runs after the render reaches the screen, not during rendering. Right after the first render, the title becomes "You clicked 0 times".

  3. Line 7document.title = 'You clicked ' + count + ' times';

    A side effect on a browser API outside React. Running it twice under Strict Mode gives the same result, so it is harmless.

  4. Line 8}, [count]);

    The effect reads count, so count is a dependency. Renders where count did not change skip the effect.

  5. Line 11<button onClick={() => setCount(count + 1)}>

    A click changes state and triggers a re-render; because count changed, the effect runs again and updates the title.

You should see
A button reading "Click to change title (0)" renders and the tab title becomes "You clicked 0 times". Each click increases the number on the button, and the title follows: "You clicked 1 times", "You clicked 2 times", and so on.

You might not need an effect

Effects are React's escape hatch: use them only to step outside React. If no external system is involved, and you just want to compute a value from props or state or respond to a user action, you do not need an effect. An unnecessary effect costs an extra render and briefly shows stale values.

Profile.jsx
import { useEffect, useState } from 'react';

// Avoid: an effect + extra state for a derived value
function ProfileSlow({ firstName, lastName }) {
  const [fullName, setFullName] = useState('');
  useEffect(() => {
    setFullName(firstName + ' ' + lastName);
  }, [firstName, lastName]);
  return <h2>{fullName}</h2>;
}

// Better: compute it while rendering
function Profile({ firstName, lastName }) {
  const fullName = firstName + ' ' + lastName;
  return <h2>{fullName}</h2>;
}
You want toPut it in
Compute a value from props/stateRender directly (useMemo if expensive)
React to a click or submitThe event handler
Reset all state when a prop changesA key prop (<Profile key={userId} />)
Connect to a timer, subscription or browser APIuseEffect + cleanup

Fetching data in an effect

Fetching in an effect can let responses arrive out of order (a race condition). Keep let ignore = false;, set ignore = true; in the cleanup, and skip setting state when a response arrives after ignore became true. The setup function itself cannot be async; declare an async function inside it and call that. Real apps usually rely on their framework's or a data library's fetching instead.

In real projects

Where this shows up in real projects

Most effects in production code are subscriptions: joining a chat room (leaving the old one and joining the new one when roomId changes), listening to window resize or scroll, opening a WebSocket, initializing a non-React widget such as a map or chart library on a DOM node, or sending a page view to analytics. Each of those has a cleanup.

Teams wrap effects in custom Hooks such as useOnlineStatus or useWindowSize to keep components clean. For data fetching, they more often rely on a framework's data loading, such as Next.js, or a library like TanStack Query than on hand-written effects, because those handle caching, retries and race conditions. In code review, ask of every new effect: which external system does it synchronize with? If there is no answer, the effect can probably go.

Common mistakes

Common mistakes

1. Setting the state the effect depends on

useEffect(() => { setCount(count + 1); }, [count]) runs whenever count changes, changes count, and loops forever. Calling setState in an effect with no dependency array at all does the same. If the update is caused by an event, move it into the handler.

2. Hiding the double run instead of fixing cleanup

Removing <StrictMode> or adding a "ran already" ref because the effect runs twice only hides the bug. In production, too, components unmount and mount again whenever users navigate away and back, so the cleanup has to be right.

3. Objects or functions recreated every render as dependencies

Writing const options = { roomId }; in the component and depending on [options] creates a new object every render, so the effect reconnects on every render. Create the object inside the effect and depend on the primitive [roomId] instead.

Mini challenge

Mini challenge: a pausable countdown

Write a countdown timer with Start/Pause and Reset. Start the interval in an effect and stop it in the cleanup; the tab title should show the remaining time as well.

  • A pure formatTime(totalSeconds) turns 90 into "01:30"
  • The interval runs only while running and not yet at 0; the cleanup calls clearInterval
  • Use an updater function (l => ...) inside the interval so the effect does not depend on left
  • At 0, show "Time's up!" and disable Start; the tab title matches the label
Countdown.jsx
import { useEffect, useState } from 'react';

export function formatTime(totalSeconds) {
  // TODO: "MM:SS" with leading zeros
}

export default function Countdown({ start = 90 }) {
  // TODO: left and running state; finished = left === 0
  // TODO: label = "Time's up!" when finished, otherwise formatTime(left)

  useEffect(() => {
    // TODO: do nothing unless running and not finished
    // TODO: start an interval that counts down by 1 every second
    // TODO: return a cleanup that clears it
  }, [/* TODO */]);

  // TODO: an effect that copies label into document.title

  // TODO: render the label, a Start/Pause button and a Reset button
}

Expected: It starts at 01:30 with a Start button. Start counts down once per second, 01:29, 01:28 ..., and Pause stops it. At 0 it shows Time's up! and Start is disabled. formatTime(90) = "01:30", formatTime(5) = "00:05".

Show hint

The effect's dependencies are [running, finished]. With an updater, setLeft(l => Math.max(l - 1, 0)), the interval never reads left. When finished turns true, the cleanup stops the interval automatically.

Show solution
Countdown.jsx
import { useEffect, useState } from 'react';

export function formatTime(totalSeconds) {
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
}

export default function Countdown({ start = 90 }) {
  const [left, setLeft] = useState(start);
  const [running, setRunning] = useState(false);
  const finished = left === 0;
  const label = finished ? "Time's up!" : formatTime(left);

  useEffect(() => {
    if (!running || finished) return;
    const id = setInterval(() => {
      setLeft((l) => Math.max(l - 1, 0));
    }, 1000);
    return () => clearInterval(id);
  }, [running, finished]);

  useEffect(() => {
    document.title = label;
  }, [label]);

  function handleReset() {
    setRunning(false);
    setLeft(start);
  }

  return (
    <div>
      <p>{label}</p>
      <button type="button" onClick={() => setRunning((r) => !r)} disabled={finished}>
        {running ? 'Pause' : 'Start'}
      </button>
      <button type="button" onClick={handleReset}>Reset</button>
    </div>
  );
}

Quick quiz 1 / 3

In production, when do the setup and cleanup of useEffect(setup, []) run?

Quick quiz 2 / 3

Setup logs 'connect' and cleanup logs 'disconnect'. In development with Strict Mode, what does the console show on mount?

Quick quiz 3 / 3

You need fullName from the firstName and lastName state. What is the best approach?

What to remember

  • useEffect runs after the render is committed and keeps a component in sync with systems outside React.
  • No array = every render, [] = once after mount, [a, b] = whenever they change; list every reactive value the effect uses.
  • Cleanup runs before a re-run and on unmount, and must undo whatever the setup did.
  • Strict Mode's setup → cleanup → setup in development exposes cleanup bugs. Derived values and event logic do not need effects.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

useEffect Hook | Thuta Learning