DEV Community

Bikash Mishra
Bikash Mishra

Posted on • Updated on

Last minute guide to React.useEffect()

React.useEffect() is one of the React hooks that manages side-effects in functional React components. You can do so much by writing so little with the help of this hook.

useEffect accepts a callback function (also called the 'effect' function), and it runs after every render (by default).

If you want your effects to run less often, you can provide a second argument – an array of values. Think of them as the dependencies for that effect.

So, let us look at some examples in which I'll be showing how you can control the behavior of useEffect.

1. When no dependencies are provided

The callback function provided as the first argument will run after every rendering.

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs after EVERY rendering
  });  
}
Enter fullscreen mode Exit fullscreen mode

2. When an empty dependencies array([]) is provided

The callback function provided as the first argument will run only once after the initial rendering.

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Runs ONCE after initial rendering
  }, []);
}
Enter fullscreen mode Exit fullscreen mode

3. When dependencies array provided has props or state values [prop1, prop2, ..., state1, state2]

The callback function provided as the first argument will run only when any dependency value changes.

import { useEffect, useState } from 'react';

function MyComponent({ prop }) {
  const [state, setState] = useState('');
  useEffect(() => {
    // Runs ONCE after initial rendering
    // and after every rendering ONLY IF `prop` or `state` changes
  }, [prop, state]);
}
Enter fullscreen mode Exit fullscreen mode

4. Effect with Cleanup

If the callback of useEffect returns a function, then useEffect() considers this as an effect cleanup.

useEffect(() => {
  // Side-effect...

  return function cleanup() {
    // Side-effect cleanup...
  };
}, dependencies);
Enter fullscreen mode Exit fullscreen mode

It's pretty common to clean up an effect after some time. This is possible by returning a function from within the effect function passed to useEffect. Below's an example with addEventListener.

() => {
  useEffect(() => {
    const clicked = () => console.log('window clicked')
    window.addEventListener('click', clicked)

    // return a clean-up function
    return () => {
      window.removeEventListener('click', clicked)
    }
  }, [])

  return <div>
    When you click the window you'll 
    find a message logged to the console
  </div>
}
Enter fullscreen mode Exit fullscreen mode

5. Multiple Effects

Multiple useEffect calls can happen within a functional component as shown below:

() => {
  // 🍟
  useEffect(() => {
    const clicked = () => console.log('window clicked')
    window.addEventListener('click', clicked)

    return () => {
      window.removeEventListener('click', clicked)
    }
  }, [])

  // 🍟 another useEffect hook 
  useEffect(() => {
    console.log("another useEffect call");
  })

  return <div>
    Check your console logs
  </div>
}
Enter fullscreen mode Exit fullscreen mode

I hope this article helps someone out there.

If you liked this post, you can find more by:

Tweet this post
Follow me on Twitter @forkbikash

Top comments (12)

Collapse
 
rmorse profile image
Ross Morsali • Edited

Great article! useEffect can be used in so many ways - I've also started using useLayoutEffect for certain things.

Also: something I learnt recently, if you add javascript to your code blocks you will get syntax highlighting πŸ₯³ dev.to/hoverbaum/how-to-add-code-h...

Collapse
 
mateusvellar profile image
Mateus V. Vellar

Works for GitHub markdown as well. You can use javascript or just js or even jsx or graphql

Collapse
 
forkbikash profile image
Bikash Mishra

Thanks @rmorse . Just edited my post after reading your blog. It was amazing.

Collapse
 
rmorse profile image
Ross Morsali

Look great!

Btw the article I linked was by someone else, I just read it recently when writing my first dev.to post πŸ˜ƒ

Thread Thread
 
forkbikash profile image
Bikash Mishra • Edited

Sorry, I didn't see thatπŸ˜…. Anyway, you are the one who helped me get in touch with the article. Thanks for that.

Collapse
 
ashvin777 profile image
Ashvin Kumar Suthar

Does useEffect dependencies watch nested object changes ?
I just want to understand whether its deep check or ref change check.

Collapse
 
forkbikash profile image
Bikash Mishra • Edited
Collapse
 
ashvin777 profile image
Ashvin Kumar Suthar

Ok basically its ref checm

Collapse
 
dhanbycode profile image
dhanbycode

Great, I always like to read detailed articles like this

Collapse
 
forkbikash profile image
Bikash Mishra

Thanks @dhanbycode .

Collapse
 
saroj8455 profile image
Saroj Padhan

Great πŸ‘

Collapse
 
forkbikash profile image
Bikash Mishra

Thank you @saroj8455