React hooks: useEffect
Tags: react, hooks, tutorial
Published: 2021-08-14 15:17:03

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rkuyddx3s2wrrhknkhho.png)

## 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.**

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

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

## 3. Cleanup function in the useEffect

[React useEffect cleanup: How and when to use it](https://dev.to/otamnitram/react-useeffect-cleanup-how-and-when-to-use-it-2hbm)

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:

```jsx
useEffect(() => {
	// effect
	API.subscribe()
	// cleanup
	return () => { API.unsubscribe() }
})
useEffect(() => {
  API.subscribe()
  return function cleanup() {
      API.unsubscribe()
  }
})
```

## 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.

```jsx
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
  }
}, [])
```

## 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.

```jsx
const [counter, setCounter] = useState(0)

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

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
- https://dev.to/otamnitram/react-useeffect-cleanup-how-and-when-to-use-it-2hbm
- https://reactjs.org/docs/hooks-effect.html