Effects: syncing with the outside world

Intermediate

Introduction

Rendering should only calculate what the page looks like. But components sometimes need to do things: start a timer, change the browser tab's title, connect to a chat server, listen for the window being resized. These side effects cannot happen during rendering, because React may render a component many times. useEffect lets you run them after React has updated the page, and stop them when they are no longer needed.

How it works

useEffect takes a setup function and a dependency array:

useEffect(() => {
  document.title = "Clicked " + clicks + " times";
}, [clicks]);

After every render in which a dependency has changed, React runs the setup function. The array decides how often:

  • [clicks]: after the first render, and again whenever clicks changes.
  • []: only once, after the component first appears.
  • no array at all: after every render, which is rarely what you want.

List every value from the component that the effect reads; a linter in real projects checks this for you. Leaving one out makes the effect use an old value.

Many effects start something that has to be stopped. The setup function can return a cleanup function, which React calls before running the effect again and when the component is removed from the page:

useEffect(() => {
  const id = setInterval(() => setSeconds((s) => s + 1), 1000);
  return () => clearInterval(id);
}, []);

Without the cleanup, hiding the timer would leave the interval running in the background, still trying to update a component that no longer exists. Note the updater function s => s + 1: the effect runs once, so it must not rely on the seconds from that first render.

Effects are for synchronising with things outside React. Many beginners use them for things that are not effects at all. A full name made from a first and last name, a filtered list or a total should be computed during rendering, not stored in state by an effect. Responses to a specific user action, such as sending a form, belong in the event handler, not in an effect.

Example

App.jsx
console.log output from the page shows here.

Line by line

  1. Timer starts an interval in an effect with [], so only once, when it appears.
  2. Each tick calls the setter with an updater, so it always adds to the latest value.
  3. The cleanup clears the interval when Timer is removed.
  4. App keeps the document title in step with clicks through an effect with [clicks].
  5. Hiding the timer removes the component, which runs the cleanup.

Expected result

The preview shows two buttons and "Running for 0 s", which counts up each second. The browser tab's title, inside the preview, becomes "Clicked 0 times" and changes as you click. "Hide timer" removes the timer and its interval stops.

In the real world

Effects connect React to everything else: analytics events when a page is viewed, WebSocket subscriptions for live data, observers that react to the size or visibility of an element, and libraries that are not written for React, such as maps and charts. Data fetching is often written with effects, though frameworks and libraries now provide better tools for it.

Common mistakes

  • Leaving out a dependency, so the effect uses a value from an old render.
  • Forgetting the cleanup, which leaks timers and subscriptions.
  • Setting state in an effect for a value that could be computed during rendering.
  • Writing an effect with no dependency array that sets state, which renders forever.

Best practices

  • Ask first whether you need an effect at all; most data transformations do not.
  • Keep one effect per concern, each with its own cleanup.
  • Use updater functions in timers and subscriptions, so the effect does not depend on changing state.

Summary

useEffect runs code after rendering to synchronise a component with something outside React. Its dependency array controls when it runs again, and the cleanup function it returns stops what it started, before the next run and when the component goes away. Values that can be calculated during rendering, and responses to specific events, do not need effects.

Quick check

1. When does an effect with the dependency array [] run?
2. What is a cleanup function for?
3. Which does not need an effect?
4. An effect reads userId but its array is []. What happens?

Key takeaways

  • Rendering must stay pure; put timers, subscriptions and changes outside React into effects.
  • The dependency array says when to run again: [] once, [x] when x changes.
  • Return a cleanup function to stop what the effect started.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.