Chapter 13 · Escape Hatches

Effects

Effects let a component synchronise with something outside React, like a chat server, a timer or a browser API, after it renders.

You will learn
  • What an Effect is, and how it differs from an event
  • How to write useEffect with dependencies and cleanup
  • Why Effects run twice in development
  • When you don't need an Effect (most of the time!)
  • The lifecycle of an Effect, Effect Events, and removing dependencies

Two kinds of logic

Some things happen because a component is on screen, not because of a click. For example: "while the chat room is visible, stay connected to the server". That's an Effect. Effects run after the commit, once the screen has updated.

Writing an Effect

Step 1: declare it

You can't call play() during rendering: the <video> doesn't exist yet, and rendering must be pure. An Effect waits until the DOM is ready.

Step 2: specify the dependencies

By default, an Effect runs after every render. Usually you want it to run only when certain values change. List them in the dependency array:

You don't choose the dependencies. Your code does. Every reactive value (prop, state, or a variable calculated from them) used inside the Effect must be listed. The linter (react-hooks/exhaustive-deps) checks this for you. If you don't want a value to be a dependency, change the code so it doesn't need it. Never just delete it from the list.

Step 3: add cleanup if needed

Return a function to undo what the Effect did. React calls it before running the Effect again, and when the component is removed from the screen.

Why does my Effect run twice?

In development, StrictMode deliberately mounts → unmounts → mounts each component, so you'll see "connect, disconnect, connect". This checks that your cleanup really undoes the setup. Don't try to stop it with a ref; fix the cleanup instead. In production it runs once.

Common Effect patterns

About fetching in Effects It works for learning, but real apps usually use a framework's data loading or a library (TanStack Query, SWR), which handle caching and race conditions for you.

You might not need an Effect

This is one of the most important pages in the docs. Many beginners overuse Effects. If there's no external system involved, you probably don't need one.

1. Calculating values from props or state? Do it during render

If the calculation is expensive, wrap it in useMemo: const visible = useMemo(() => filterTodos(todos, tab), [todos, tab]);

2. Responding to a user action? Use the event handler

3. Resetting state when a prop changes? Use a key

SituationUse instead of an Effect
Deriving data from props or stateA calculation during render (plus useMemo if it's slow)
Something caused by a click or submitThe event handler
Resetting all state when an ID changesA key
Notifying the parent about a changeCall the parent's onChange in the same event handler
Syncing with an external system✅ This is what Effects are for

The lifecycle of an Effect

Components mount, update and unmount. Effects are simpler: each one does only two things, start syncing and stop syncing, and it may do that many times.

Think from the Effect's point of view: "how do I start and stop syncing for this roomId?" React handles when.

Separating events from Effects

Sometimes an Effect needs to read a value without reacting to it. Example: show a notification in the current theme when the chat connects, but don't reconnect when the theme changes.

useEffectEvent creates a function that behaves like an event handler: it sees the latest values but isn't reactive. Use it only for code called from inside Effects.

Removing unnecessary dependencies

More examples

Example 1: fetching a list with loading and error states

Example 2: a keyboard shortcut (Escape closes a modal)

The listener exists only while the modal is on screen. When the modal unmounts, the cleanup removes it.

Example 3: saving to localStorage

Example 4: focusing on mount

Example 5: the infinite loop trap

An Effect that sets state with no dependencies (or with the very state it sets as a dependency) loops forever. Ask yourself: "is this really syncing with something outside React?"

Recap

  • Effects run after rendering to sync with external systems.
  • useEffect(setup, deps): no array = every render, [] = mount only, [a, b] = when a or b change.
  • Return a cleanup function. Running twice in development tests it.
  • Don't use Effects for derived data, for user events, or for resetting state.
  • List every reactive value as a dependency. To remove one, change the code, not the list.

Exercises

1. Document title

Make a counter that also shows the count in the browser tab title (document.title = ...).

Show solution

2. A live clock

Show the current time, updated every second. Remember the cleanup!

Show solution

3. Remove the Effect

Show solution

4. Effect or not? 🟢 easy

For each task, say whether it needs an Effect: (a) show the total price of the cart, (b) connect to a WebSocket while a page is open, (c) send analytics when the "Buy" button is clicked, (d) listen for window resize, (e) reset a form when a different user is selected.

Show answer

(a) No: calculate it during render. (b) Yes. (c) No: use the event handler. (d) Yes (subscribe and clean up). (e) No: use key.

5. Autofocus 🟢 easy

Make a login form whose username field is focused automatically when it appears.

Show solution

(For this simple case, the autoFocus attribute also works: <input autoFocus />.)

6. Remember the theme 🟢 easy

Make a light/dark toggle whose choice survives a page refresh (save it to localStorage with an Effect, and read it with lazy initial state).

Show solution

7. Mouse tracker 🟡 medium

Show the pointer's x/y position live, using a pointermove listener on window. Don't forget the cleanup.

Show solution

8. Escape to close 🟡 medium

In your sample-test-react app, make the Todo pop-up close when you press Escape. The listener should exist only while the pop-up is open.

Show solution

9. Fetch by ID with prev/next 🟡 medium

Show a post from https://jsonplaceholder.typicode.com/posts/{id}, with "Prev" and "Next" buttons that change id. Use the ignore flag so fast clicking never shows the wrong post.

Show solution

10. Countdown timer 🔴 hard

Build a 10-second countdown with Start, Pause and Reset buttons. Show "⏰ Time's up!" at 0. The interval should run only while the timer is running and above 0.

Show solution

Because seconds is a dependency, the interval restarts every second. That's fine, and it stops cleanly at 0. An alternative keeps one interval and uses only the updater function, with [running] as the dependencies.