useEffect React hook, how to use

Find out what the useEffect React hook is useful for, and how to work with it!

Check out my React hooks introduction first, if you’re new to them.

One React hook I use a lot is useEffect.

import React, { useEffect } from 'react'

The useEffect function runs when the component is first rendered, and on every subsequent re-render/update.

React first updates the DOM, then calls the function passed to useEffect().

Example:

const { useEffect, useState } = React

const CounterWithNameAndSideEffect = () => {
  const [count, setCount] = useState(0)
  const [name, setName] = useState('Flavio')

  useEffect(() => {
    console.log(`Hi ${name} you clicked ${count} times`)
  })

  return (
    <div>
      <p>
        Hi {name} you clicked {count} times
      </p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={() => setName(name === 'Flavio' ? 'Roger' : 'Flavio')}>
        Change name
      </button>
    </div>
  )
}

TIP: if you’re an old-time React dev and you’re used to componentDidMount, componentWillUnmount and componentDidUpdate events, this replaces those.

You can optionally return a function from the function you pass to useEffect():

useEffect(() => {
  console.log(`Hi ${name} you clicked ${count} times`)
  return () => {
    console.log(`Unmounted`)
  }
})

The code included in that function you return will execute when the component is unmounted.

You can use this for any “cleanup” you need to do.

For old timers, this is like componentWillUnmount

useEffect() can be called multiple times, which is nice to separate unrelated logic.

Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip executing the function, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for.

React will only re-run the side effect if one of the items in this array changes.

useEffect(
  () => {
    console.log(`Hi ${name} you clicked ${count} times`)
  },
  [name, count]
)

Similarly you can tell React to only execute the side effect once (at mount time), by passing an empty array:

useEffect(() => {
  console.log(`Component mounted`)
}, [])

This ☝️ is something I use all the time.

Example on Codepen:

See the Pen React Hooks example #3 side effects by Flavio Copes (@flaviocopes) on CodePen.

Download my free React Handbook!