DEV Community

Cover image for React hooks: useEffect
Abdullah Furkan Özbek
Abdullah Furkan Özbek

Posted on • Updated on

React hooks: useEffect

1. useEffect hook

useEffect lets you perform side effects in function components. For example you want to fetch some data after the component is loaded. You can do this by using useEffect hook.

React Illustration

2. Declaring useEffect

By default, useEffect runs both after the first render and after every update. We can customize this by so called dependencies to it as a second argument which we will cover later in this tutorial.

In this example we added useEffect and give it a callback to run, which is our effect.

const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
}
Enter fullscreen mode Exit fullscreen mode

3. Cleanup function in the useEffect

React useEffect cleanup: How and when to use it

The useEffect hook is built in a way that if we return a function within the method, this function will execute when the component gets disassociated.

This is very useful because we can use it to remove unnecessary behavior or prevent memory leaking issues. Also React performs the cleanup when the component unmounts. However, effects run for every render and not just once.

This is why React also cleans up effects from the previous render before running the effects next time.


So, if we want to cleanup a subscription, the code would look like this:

useEffect(() => {
    // effect
    API.subscribe()
    // cleanup
    return () => { API.unsubscribe() }
})
useEffect(() => {
  API.subscribe()
  return function cleanup() {
      API.unsubscribe()
  }
})
Enter fullscreen mode Exit fullscreen mode

4. Updating the state of an unmounted component

For this reason cleanup the effect you might have in your components. For example if you are changing the loading state of your component based on fetching the data you might need to add cleanup so that even users change the components you make sure there is no leak in the memory.

const [loading, setloading] = useState(true)

useEffect(() => {
  fetchAPI.then(() => {
      setloading(false)
  })
}, [])

// With cleanup
useEffect(() => {
  let mounted = true
  fetchAPI.then(() => {
    if (mounted) {
        setloading(false)
    }
  })

  return function cleanup() {
    mounted = false
  }
}, [])
Enter fullscreen mode Exit fullscreen mode

5. Skipping Effects

We can also optionally add a dependency which we described earlier to the useEffect. It is need to be in the array and the effect will be called until the array changes.

const [counter, setCounter] = useState(0)

useEffect(() => {
    console.log("Next Counter: ", counter)
}, [counter]) // Run this effect if counter changes
Enter fullscreen mode Exit fullscreen mode

For example if our counter variable is 3 and our component rendered again it will try to take a look the again the counter variable. Lets say we update it to 4. React will take a look at 3 ≠ 4 so it will render the effect again.

6. Links

Top comments (0)