useEffect in Depth — React

The function an effect returns is its cleanup function. React runs it when the component unmounts (is removed from the page), and before the effect runs again…

You set up a timer in a component, move to another page, then open the console: tick is still printed every second, even though the timer is no longer on screen. Nobody ever switched it off.

An effect that switches on something that keeps running, like a timer, an event listener or a request to a server, must also be able to switch it off. The way to do it: the effect returns a function, called the cleanup function. React calls it when the component leaves the page, and before that effect runs again. It's like a kitchen tap: if you walk away without closing it, the water keeps running even though nobody is using it. The tap is the timer or the listener, and walking away from the kitchen is the component leaving the page. Cleanup is the "close the tap" note you hand to React the moment you open the tap.

Cleanup: close what you open

Two terms from the previous lesson. Mount means the component appears on the page. Unmount means the component is removed from the page, for example because {shown && <Timer />} turned false.

This Timer component raises a number every second, and switches its timer off on unmount:

function Timer() {
  const [seconds, setSeconds] = useState(0)

  useEffect(() => {
    const id = setInterval(() => {
      setSeconds((s) => s + 1) // up by 1 every second
      console.log('tick')
    }, 1000)

    return () => clearInterval(id) // cleanup: stop this interval
  }, []) // [] = set up once, when Timer mounts

  return <span id="timer">{seconds}</span>
}
Event With cleanup Without cleanup
Timer mounts 1 interval 1 interval
Timer unmounts clearInterval, 0 intervals 1 interval, still running
Mounts again 1 interval 2 intervals
Unmount and mount again, 2 more times 1 interval 4 intervals

Without cleanup, every mount sets up a new interval and the old ones never stop. If Timer is shown again three times, 4 intervals run together, and the console gets 4 ticks per second. The number on screen still goes up by 1 per second, because React ignores setSeconds from a component that's already gone. So this bug often goes unnoticed. A bug like this is called a memory leak: something no longer in use that still uses the computer's memory and processing power.

When cleanup runs

React calls the cleanup at two moments:

  1. When the component unmounts.
  2. Before the effect runs again because something in its dependency array changed. The old render's cleanup runs first, then the new setup (the effect's main code).

An effect that only replaces something needs no cleanup. The tab title, for example:

function App() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    document.title = 'Count: ' + count // the tab title follows the number
  }, [count]) // runs again every time count changes

  return (
    <div>
      <span id="count">{count}</span>
      <button id="add" onClick={() => setCount((c) => c + 1)}>+1</button>
    </div>
  )
}

At first the tab title is Count: 0. After 1 click on the #add button it's Count: 1, after 2 clicks Count: 2. Each effect overwrites the old title, so there's nothing to clean up. Cleanup is only required for things that keep running: intervals, listeners, requests, connections.

One thing not to do: don't change a state that's in the dependency array from inside that same effect. useEffect(() => { setCount(count + 1) }, [count]) changes count. Because count changed, the effect runs again, which changes count again, forever. That's an infinite loop (a loop that never ends).

Event listeners are removed too

This effect adds a keydown listener to window. When the Escape key is pressed, setOpen(false) closes something that's open, such as a menu:

useEffect(() => {
  function onKey(e) {
    if (e.key === 'Escape') setOpen(false)
  }
  window.addEventListener('keydown', onKey)
  return () => window.removeEventListener('keydown', onKey)
}, [])

removeEventListener needs the same function that was added, which is why onKey has a name. If addEventListener and removeEventListener each get their own arrow function, those are two different functions, even when the code inside is the same. So the listener is never removed.

Race condition: the old answer arrives last

A race condition happens when two requests race. The winner (the answer that ends up on screen) is the one that arrives last, not the answer for your last pick. Say the server takes 1.5 seconds for Andi and 0.4 seconds for Budi. You pick Andi, then half a second later pick Budi:

Time What happens No ignore With ignore
0 s pick Andi, Andi's request is sent
0.5 s pick Budi: Andi's effect is cleaned up, Budi's request is sent Andi's ignore becomes true
0.9 s Budi's answer arrives shows Budi shows Budi
1.5 s Andi's answer arrives shows Andi, wrong person thrown away

This Profile component uses an ignore guard so the old answer is thrown away:

function Profile({ userId }) {
  const [user, setUser] = useState(null)

  useEffect(() => {
    let ignore = false // this effect's own guard

    fetchUser(userId).then((data) => {
      if (!ignore) setUser(data) // a stale answer is thrown away
    })

    return () => {
      ignore = true // userId changed: this effect is no longer in use
    }
  }, [userId])

  return <p>Profile: {user ? user.name : 'loading...'}</p>
}

fetchUser(userId) gets the data from the server, for example fetch('/api/users/' + userId).then((res) => res.json()). Every effect has its own ignore. As soon as userId changes, the old effect's cleanup sets its ignore to true. So the answer for the old effect is thrown away when it arrives.

The second way, AbortController, really cancels the old request:

useEffect(() => {
  const controller = new AbortController()

  fetch('/api/users/' + userId, { signal: controller.signal })
    .then((res) => res.json())
    .then(setUser)
    .catch((err) => {
      if (err.name !== 'AbortError') console.error(err)
    })

  return () => controller.abort() // cancel the old request
}, [userId])

{ signal: controller.signal } connects this fetch to its controller. controller.abort() makes fetch fail with an error named AbortError. That error is on purpose, so the catch ignores it.

Stale closure: the frozen number

This effect is like the Timer above, but it adds with seconds + 1:

useEffect(() => {
  const id = setInterval(() => {
    setSeconds(seconds + 1) // seconds here is always 0
  }, 1000)
  return () => clearInterval(id)
}, [])

This effect runs once, after the first render, when seconds is still 0. The function inside setInterval remembers seconds from that render (a closure, which you know from the JavaScript track). Every second that function calculates 0 + 1, so the number freezes at 1. An old value that keeps getting carried along like this is called a stale closure. The fix is the updater function: setSeconds((s) => s + 1). React always gives it the latest value as s.

⚠️ Cleanups written wrong, and effects that run twice

TL;DR: The function an effect returns is its cleanup function. React runs it when the component unmounts (is removed from the page), and before the effect runs again because something in its dependency array changed. Anything that keeps running (a timer, a listener, a request) must be cleaned up. setInterval is cleaned up with return () => clearInterval(id). addEventListener is cleaned up with removeEventListener using the same function. A request is guarded with an ignore variable or controller.abort(), so an old answer doesn't overwrite the new one (a race condition). document.title = 'Count: ' + count with [count] needs no cleanup. Don't change a state that's in the dependency array from its own effect, because that's an infinite loop (a loop that never ends). In an interval, add with setSeconds((s) => s + 1), not seconds + 1, so you don't get a stale closure (a number frozen at an old value).

⚡ Cleanup: close what you open

Write:

useEffect(() => {
  const id = setInterval(() => {
    setSeconds((s) => s + 1) // up by 1 every second
  }, 1000)

  return () => clearInterval(id) // cleanup: stop this interval
}, [])

Meaning: setInterval switches on a timer that raises the state seconds every second, and clearInterval(id) switches it off. The function an effect returns is called the cleanup. React keeps it and only calls it later. What's returned is the function (() => ...), not the result of clearInterval(id).

⚡ When cleanup runs

Guess first: a Timer component sets up an interval as above, but with no cleanup. Timer unmounts (is removed) and mounts again three times. How many intervals are running together?

Four: one from the first mount, three from mounting again. Every mount sets up a new interval, and the old ones never stop.

Meaning: React calls the cleanup when the component unmounts, and before the effect runs again because something in its dependency array changed.

⚡ A number that freezes

Write:

useEffect(() => {
  const id = setInterval(() => {
    setSeconds(seconds + 1) // seconds here is always 0
  }, 1000)
  return () => clearInterval(id)
}, [])

Meaning: An effect with [] only sees seconds from the first render, when its value is still 0. Every second the interval calculates 0 + 1, so the number freezes at 1. This problem is called a stale closure. Use the updater: setSeconds((s) => s + 1).

What you will learn