Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Effects as Synchronization, Not Lifecycle

See effects as a way to keep an external system in step with what is on screen, and learn how the dependency array and cleanup function decide when React re-synchronises.

Contentsand lesson path

What you will learn

  • Decide when an effect is needed versus computing during render or handling logic in an event handler, and write effects with complete dependencies and cleanup.

Prerequisites: React Components & State, Async JavaScript & Fetch

01. Why it matters

Part of what a component does happens outside React. A browser tab title, a WebSocket connection, a timer, a subscription to a window event: none of these are values you render, and none of them wait politely for React. They change on their own, and something has to keep them in step with what is on the screen.

An effect is that something. After React has committed your JSX to the screen, it calls your effect function; whenever the values the effect depends on change, React first undoes the previous run and then runs it again. The mental model that makes this workable is in the skill summary already: an effect does not react to a moment in time, it synchronises a component with an external system. You describe the target state — the tab title should read like this, one interval of this length should be running — and React works out when to run your code and when to undo it.

Two habits separate people who are comfortable with effects from people who fight them. First, reach for an effect only when there really is an external system to synchronise with: a large share of the effects in real code bases do work that rendering or event handlers do better, and the next lesson is devoted to spotting them. Second, for every effect you do write, ask the same two questions: what must happen when it re-runs, and what must happen when it stops? The answers are the dependency array and the cleanup function — the two halves of every effect this lesson teaches.

02. An effect that synchronises something real

Here is a search box that keeps the browser tab title in step with what the user has typed. The title is a property of document — an external system React does not manage — so this is a genuine synchronisation job:

JSX · title-sync.jsx
import { useEffect, useState } from 'react';

export default function PageTitle() {
  const [query, setQuery] = useState('');
  useEffect(() => {
    document.title = query
      ? `Searching for "${query}" · Book Finder`
      : 'Book Finder';
  }, [query]);
  return (
    <label>
      Search books
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        aria-label="Search books"
      />
    </label>
  );
}
Expected output (typed in Chromium; the tab title after each step)
initial document.title          -> Book Finder
after typing "Hooks"            -> Searching for "Hooks" · Book Finder
after typing "Effects"          -> Searching for "Effects" · Book Finder
after clearing the input        -> Book Finder

Read the recording with the model in mind. On mount, the effect ran once and set the plain title. Every keystroke changed query, and query is in the dependency array, so React ran the effect again after committing the new input value. Clearing the input made the dependency fall back to its first value, and one more run restored the bare title. Nowhere is there code that decides when to update: the dependency array decides, and the effect body only describes the target state.

If you worked through the DOM skill, compare this with the manual approach of listening to input events and writing to the title yourself. The listener is gone because React already knows when query changes; so is the teardown code, because the effect mechanism handles it — as the rest of this lesson shows.

03. The dependency array: when to re-synchronise

The array is the contract between your effect and the render. React compares each element with its previous value using Object.is after every commit, and re-runs the effect when any of them differ:

  • No array (useEffect(fn)): runs after every render. Almost never what you want.
  • Empty array ([]): runs once after mount, and its cleanup runs at unmount. Right for effects that read nothing reactive, such as a one-off connection for data that never changes.
  • [query]: runs after mount and after every commit in which query differs from the last time.

The rule that keeps this honest: every reactive value the effect body reads must be in the array — every prop, every piece of state, anything declared in the component body. Leave one out and the effect does not fail loudly; it closes over a stale value and quietly keeps doing the old work, which is exactly the kind of bug that survives a casual test. The react-hooks/exhaustive-deps rule from eslint-plugin-react-hooks, part of the lint config the Vite and Next.js starters generate, flags missing dependencies, so leave it enabled rather than memorising the list. (Values React knows are stable — state setters, refs, constants defined outside the component — do not need to be listed.)

If the dependency list you end up with feels wrong, the usual cause is that the effect reads too much. Often the right fix is to move the unneeded values out of the effect, or to drop the effect altogether — a decision the next lesson walks through in detail.

04. Cleanup: what happens on re-run and unmount

Starting something is half of an effect; stopping it is the other half. If the effect body returns a function, React calls that function before every re-run and once more at unmount. That is the whole mechanism, and it is what makes re-running safe: the old interval, subscription or connection is torn down before the new one starts.

Watch it happen. This component runs a ticker whose interval gets shorter when you press a button, logging each step:

JSX · ticker.jsx
import { useEffect, useState } from 'react';

export default function Ticker() {
  const [ms, setMs] = useState(1000);
  useEffect(() => {
    console.log(`effect: start ${ms} ms interval`);
    const id = setInterval(() => console.log('tick'), ms);
    return () => {
      clearInterval(id);
      console.log(`cleanup: stop ${ms} ms interval`);
    };
  }, [ms]);
  return (
    <button type="button" onClick={() => setMs(500)}>
      Faster
    </button>
  );
}
Expected output (mount, wait one second, click Faster, wait half a second, unmount)
effect: start 1000 ms interval
tick
cleanup: stop 1000 ms interval
effect: start 500 ms interval
tick
cleanup: stop 500 ms interval

The sequence is worth memorising: cleanup of the old run, then the new run. Skip the cleanup and nothing seems wrong while the component mounts once and never changes — but the first re-run starts a second interval beside the first, and the ticks double. The same trap catches subscriptions, observers and sockets, and it is invisible in code review until something re-synchronises.

05. Strict Mode: the mount rehearsal

In development, inside <StrictMode> (which Vite and Next.js starters turn on), React mounts every component twice: it runs the effect, immediately runs its cleanup, then runs the effect again. This is a rehearsal with a simple verdict — an effect with correct cleanup survives it, and one without leaves duplicate timers or listeners behind, failing the rehearsal loudly.

Mounting the same Ticker under Strict Mode in development logs this:

Expected output (mount under Strict Mode, development only)
effect: start 1000 ms interval
cleanup: stop 1000 ms interval
effect: start 1000 ms interval

In a production build the component mounts once. So do not "fix" the double run — it is diagnostic output, not a bug. Fix the effect so the rehearsal passes, which in practice means: start nothing you do not stop.

06. Check your understanding

Practice check · 3 questions

Synchronisation, dependencies and cleanup

Three quick calls before you start deleting effects.

Q1. A chat component has one effect that connects a WebSocket, with [roomId] as its dependency and a cleanup that closes the socket. The user switches roomId from "general" to "random". What does React do?
Q2. Which of these jobs is a good fit for an effect?
Q3. An effect fetches results for `query` and `page`, but its dependency array only lists [query]. What is the consequence?
Practice only: not graded, not saved, not evidence.

07. Apply it

This feeds the skill's practice project, a book-search page. Pick one external system your current project touches — a tab title, a timer, a subscription — and write its effect deliberately:

  1. Write the effect body so it describes a target state, not a sequence of steps ("the title reads X", "one interval is running").
  2. List every reactive value the body reads, then check the array against that list.
  3. Write the cleanup: stop the timer, close the connection, restore the title.
  4. Run the component under Strict Mode and watch the console: you should see run, cleanup, run on mount, and cleanup before every re-run.

If you cannot name the external system, you probably do not need the effect — hold that thought for the next lesson.

08. Review prompt

Without looking back: what are the three forms of the dependency array and when does each re-run? In what order do cleanup and the effect run when a dependency changes? What does Strict Mode do on mount in development, and what is it rehearsing? And which three jobs — tab title, click handling, formatting a price — go to which mechanism?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check