Skip to content

useEffect React hook, how to use

The Valley of Code

Your Web Development Manual

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().


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 (
        Hi {name} you clicked {count} times
      <button onClick={() => setCount(count + 1)}>Click me</button>
      <button onClick={() => setName(name === 'Flavio' ? 'Roger' : 'Flavio')}>
        Change name

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 () => {

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.

  () => {
    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
→ Read my full React Tutorial on The Valley of Code
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)