useEffect Basics — React

A side effect is work outside what a component shows, such as changing document.title, printing with console.log or saving to localStorage. Side effects go…

Open WhatsApp Web, and a message comes in: the browser tab's title changes to "(3) WhatsApp". That tab title isn't part of what a component shows. The tab title is outside the page, and changing it needs a special place in React.

A component's main job is to calculate what to show from its state and props. But sometimes a component has to touch something outside what it shows: change the browser tab's title, write to the console, save to localStorage. Things like these are called side effects, and their place is the useEffect hook. The code inside useEffect runs after React has finished updating the page.

A render and an effect are like a bank teller and the queue number board on the wall. The teller serves customers at the desk: that's the render. The board on the wall is outside the desk, and it changes after the teller calls the next number: changing the board is the effect. The board only needs changing when the number changes, not every time the teller changes pens. In React, the queue number is a value that React watches, and the list of "change the board when this changes" is called the dependency array.

Side effects in useEffect

This component prints one line to the console from inside useEffect:

import { useEffect } from "react"

function App() {
  useEffect(() => {
    console.log("Component loaded!")
  }, [])

  return <p>Check the console</p>
}

The tab title is outside what the component shows too, so changing it is a side effect:

function App() {
  useEffect(() => {
    document.title = "Learning React" // the browser tab's title
  }, [])

  return <h1>Look at the tab title!</h1>
}

Why not write it directly in the component body? Code in the body runs on every render, and a render should only calculate what to show. Inside useEffect, you decide when the side effect runs.

The dependency array: when an effect runs again

This counter has two states: count for the number of clicks, and dark for the theme. Its effect writes count into the tab title:

function Counter() {
  const [count, setCount] = useState(0)
  const [dark, setDark] = useState(false)

  useEffect(() => {
    document.title = `Clicks: ${count}`
  }, [count])

  return (
    <div className={dark ? "dark" : "light"}>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setDark(!dark)}>Change theme</button>
    </div>
  )
}

Before you read on, take a guess: you press Change theme, which changes dark, and the component re-renders. Does the [count] effect run again or not?

After every render, React compares what's in the array with what was in it on the render before. Something changed? The effect runs. All the same? The effect is skipped.

Event Re-render? count Effect [count]
Mount yes 0 runs, title Clicks: 0
Click +1 yes 1 runs, because 0 became 1. Title Clicks: 1
Change theme yes 1 skipped, count is still 1
Click +1 yes 2 runs, title Clicks: 2

Changing the theme does cause a re-render, but count didn't change, so the effect doesn't run.

A summary of what goes in the dependency array and when the effect runs (fn is the effect function):

Written The effect runs
useEffect(fn, []) once, on mount
useEffect(fn, [count]) on mount, then every time count changes
useEffect(fn, [a, b]) on mount, then every time a or b changes
useEffect(fn) after every render

With no array at all, the effect runs after every render. A component that renders 3 times (the first render included) runs its effect 3 times.

Cleanup, and why the log can show double

If an effect returns a function, that function is called the cleanup. React calls it at two moments: before the same effect runs again, and when the component is removed from the page (unmount). In the Lab, every new effect runs line comes after a cleanup line from the effect before it. How to use a cleanup is covered in the next lesson, useEffect in Depth.

During development, a React project is usually wrapped in <StrictMode>. In that mode React deliberately runs effects on mount twice (effect, cleanup, effect again) to check your cleanup. So Component loaded! can be printed twice on your laptop. In a production build (the version that users use), the effect runs only once. The double log isn't a bug in your code.

⚠️ Effects that run too often, or never run again

TL;DR: A side effect is work outside what a component shows, such as changing document.title, printing with console.log or saving to localStorage. Side effects go inside the function fn in useEffect(fn, deps). React runs fn (the effect) after the render appears on the page. What's in deps (the dependency array) decides when the effect runs. [] means once on mount (when the component first appears). [count] means on mount and every time count changes. No array means after every render (3 renders, 3 runs). A render that doesn't change what's in the array skips the effect. The function an effect returns is its cleanup, which runs before the next effect and on unmount (when the component is removed). In development, StrictMode (a wrapper that checks your code) runs mount effects twice, in production once.

⚡ Side effects go in useEffect

Write:

useEffect(() => {
  console.log("Component loaded!")
}, [])

Meaning: A side effect is work outside what a component shows, such as printing to the console or changing the tab title. useEffect takes a function holding the side effect, then a dependency array (the values React watches, here []). React runs that function (called the effect) after the first render appears on the page. That moment is called mount. [] means just once, on mount.

⚡ The dependency array decides when

Write:

useEffect(() => {
  document.title = `Clicks: ${count}`
}, [count])
Guess first: this component also has another state, dark, which the Change theme button changes. You press that button, and the component re-renders. Does the [count] effect run again?

No. React only runs the effect again when something in the array changed, and count didn't.

Meaning: count is a state that holds the number of clicks. [count] means the effect runs on mount and every time count changes. With no array, the effect runs after every render.

⚡ Double logs during development

Meaning: A React project is usually wrapped in <StrictMode> during development. In that mode React deliberately runs effects on mount twice to check your cleanup (the function an effect returns). So Component loaded! can print twice on your laptop. In a production build (the version that users use), only once.

What you will learn