Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 132 ยท Hooks

Effects with useEffect

Learn useEffect in React - synchronizing with external systems, when effects run after render, the setup and cleanup lifecycle, StrictMode's extra setup, and effects versus event handlers.

Rendering a component is supposed to be a calculation: props and state go in, JSX comes out, and nothing else in the world changes. But real apps must touch things React does not control: the browser tab title, a timer, a WebSocket, a map widget, an analytics service. Those jobs are called side effects, and the hook for them is useEffect.

The trick to understanding useEffect is to stop thinking "run this when the component mounts" and think synchronize. An effect says: "after rendering, make this outside thing match the current props and state, and here is how to undo it." React runs the setup after the screen has been updated, and runs the undo (the cleanup) before the next setup and when the component leaves the page. This lesson shows the mechanics, the lifecycle, why React sometimes runs your setup twice in development, and how to decide between an effect and an event handler.

Your first effect

useEffect takes a function, called the setup. React calls it after the component has rendered and the changes have been committed to the DOM.

When does an effect run?

Click the button twice and read the console. You see render, count = 0 followed by effect ran, count = 0, then the same pair for 1 and 2. Rendering always happens first; the effect always comes after, and it sees the values from that render (like every other closure in React, see state is a snapshot). With no second argument the effect runs after every render. That is rarely what you want, which is where the dependency array comes in. We keep it simple here and cover the array in depth in Effect Dependencies.

Synchronizing with something outside React

The classic first use is the browser tab title, because the title lives outside React's tree. Here the effect keeps document.title in step with a piece of state:

Keeping document.title in sync

The array [unread] tells React "this effect only needs to run again when unread has changed". The preview is a separate document, so the title change is visible only in the console log here, but in a real page you would see it in the browser tab. (React 19 also lets you render a <title> element directly, which is often nicer for page titles; effects stay the right tool for things with no JSX equivalent.)

Notice what the effect does not do: it never calls setState to copy anything. It reads state and pushes it into the outside world. If you catch yourself using an effect only to calculate one piece of state from another, stop; You Might Not Need an Effect explains the better way.

Setup and cleanup

Many external systems need connecting and disconnecting: a socket, a subscription, a timer. For these your setup function can return a cleanup function. React runs it:

  • before running the effect again, with the old values it closed over, and
  • when the component is removed from the screen.

So the full lifecycle for an effect that depends on roomId is:

  1. Render with room "general". React commits, then runs setup: connect to general.
  2. The user switches to "music". React renders again, commits, then runs the cleanup from the previous render (disconnect from general), then runs the new setup (connect to music).
  3. The component unmounts. React runs the last cleanup (disconnect from music).

Think of setup and cleanup as a pair that must always leave things as they were. Each cycle of start and stop belongs to one set of values.

Setup and cleanup in order

Switch the room to music, then press "Leave chat". The console shows connect to general, then disconnect from general, connect to music (the cleanup of the old cycle always comes first), and finally disconnect from music when the component unmounts. The cleanup for a cycle uses the roomId of that render, not the latest one, which is why it disconnects from the right room.

If your cleanup does not exactly reverse your setup, you have a bug waiting to happen. Subscribed: unsubscribe. Started a timer: clear it. Added a listener: remove the same function. Opened a connection: close it. Cleanup, Subscriptions and Timers has many more patterns.

A real subscription

Here is a typical subscription. The effect attaches a keydown listener to the window and the cleanup removes it, so that listeners do not pile up every time the component updates or reappears.

Subscribing to window key events

Click the preview to focus it and type a few keys; they show up in the list (only the last five are kept, using a functional update). Hide the logger and the console prints listener removed: from then on typing does nothing and nothing leaks. Forget the cleanup and every show/hide would leave an extra listener behind, all still calling setKeys on an unmounted component's old state.

Why setup runs twice in development

If your app (or a framework such as Next.js or a Vite template) wraps the tree in <StrictMode>, React deliberately does one extra cycle in development only when a component first mounts: setup, then cleanup, then setup again. This stress test checks that your cleanup really reverses your setup. A correct effect cannot tell the difference between "ran once" and "ran, was undone, ran again". Production builds only run it once.

StrictMode's extra setup and cleanup

The log reads connecting..., disconnecting..., connecting.... The first two lines are the stress test; the last one is the connection you keep. Our editor runs React's development build, so you see the same thing here as in a Vite or Next.js dev server. Now compare a correct effect with a leaky one, counting the listeners that are still registered:

A leaky effect exposed by StrictMode

The good effect reports 1 both times it runs, because the cleanup undid the first setup. The leaky effect reports 1 and then 2: one component, two listeners. In a real app that means duplicated handlers, duplicate network connections or doubled analytics. That is the signal StrictMode gives you: if doubled behaviour looks wrong, a cleanup is missing. Fix the cleanup rather than removing StrictMode.

Some effects are not about connecting at all, for example "send an analytics event when this page is shown". These have nothing to undo, and the double run in development is harmless (analytics code is often written to ignore duplicates). Do not hack around it with a flag that remembers "already ran"; that hides real bugs.

Effects versus event handlers

The most common mistake with effects is using them for things that should happen because the user did something. The rule of thumb:

  • If code runs because a particular interaction happened (click, submit, key press), put it in the event handler. You know exactly what caused it.
  • If code runs because the component is displayed with certain values, and has to stay in step with them, it is an effect.
Event handler or effect?

Switching products logs a page view (the effect), changing the quantity logs nothing, and pressing Buy logs the order. If the purchase were an effect watching quantity, it would fire when the user merely edits the number. An effect that responds to a click by watching state is a classic bug: you lose the information about why it ran, and it may run at the wrong moments.

What an effect is for

Good uses, where React state must stay in sync with something outside React:

  • Subscribing to browser or third-party events (resize, online status, sockets).
  • Connecting to servers, timers, media players or maps.
  • Setting up non-React widgets or libraries that manipulate the DOM.
  • Sending analytics when something appears.
  • Fetching data when a component shows (with care; see Fetching Data).

Not good uses:

  • Calculating values from props and state (do it in render).
  • Resetting state when a prop changes (use a key).
  • Responding to a user action (use the event handler).
  • Passing data up to a parent (call the parent's callback in the handler).

Timing: when exactly does it run?

React renders, applies changes to the DOM, lets the browser paint, and then typically runs effects. That is why effects should not make the first paint wait. If you must measure the DOM and change the layout before the user sees anything, use useLayoutEffect (covered later). When an effect updates state, React renders again, which is allowed but often a sign that the logic belongs elsewhere.

A few more facts worth keeping in mind:

  • Effects are per component instance. Two copies of ChatRoom run two separate connections.
  • An effect's function can't be async itself, because it must return either nothing or a cleanup function, not a promise. Define an async function inside and call it.
  • Effects never run on the server during server rendering; they run only in the browser.
  • Anything that is read inside the effect and can change over time belongs in the dependency array. The next lesson covers it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does the setup function of useEffect run?

    Effects run after the render has been committed. With a dependency array they run again only when a dependency changed.
  2. 2. A component's effect depends on roomId and returns a cleanup. The user changes the room. In what order do things happen?

    React cleans up the previous cycle before starting the next one, and the cleanup sees the values from the render that created it.
  3. 3. In development StrictMode you see the log connect, disconnect, connect on mount. What does it mean?

    StrictMode runs an extra setup and cleanup cycle in development only. A correct effect behaves the same whether it ran once or was undone and re-run.
  4. 4. Where should code that places an order when the user presses Buy live?

    It happens because of a specific interaction, so it belongs in the event handler. An effect would run for the wrong reasons.
  5. 5. Why can't you write useEffect(async () => { ... })?

    Declare an async function inside the effect and call it. The outer function stays synchronous so it can return a cleanup function.

Summary

  • An effect synchronizes your component with something outside React; it runs after React renders and commits.
  • The setup may return a cleanup. React runs the old cleanup before the next setup and on unmount, so each cycle closes over its own values.
  • Always write a cleanup that exactly reverses the setup (remove listeners, clear timers, close connections).
  • In development, StrictMode runs an extra setup, cleanup, setup cycle on mount to expose missing cleanups; production runs it once.
  • Use event handlers for work caused by user actions and effects for work caused by being on screen with certain values.
  • Don't use effects to compute derived state or to reset state; see the lesson on avoiding unnecessary effects.

Next: Effect Dependencies