Skip to content

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.


→ Get my React Beginner's Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about react: