/

How to Use the useEffect React Hook

How to Use the useEffect React Hook

Discover the usefulness of the useEffect React hook and learn how to work with it!

If you’re new to React hooks, I recommend checking out my React hooks introduction first.

One of the React hooks that is commonly used is useEffect.

1
import React, { useEffect } from 'react'

The useEffect function is executed when the component is first rendered and on every subsequent re-render or update.

React first updates the DOM, then calls the function passed to useEffect().

Here’s an example of how to use the useEffect hook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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>
)
}

A tip for old-time React developers: If you’re used to componentDidMount, componentWillUnmount, and componentDidUpdate events, the useEffect hook replaces those.

You can optionally return a function from the function passed to useEffect():

1
2
3
4
5
6
useEffect(() => {
console.log(`Hi ${name}, you clicked ${count} times`)
return () => {
console.log('Unmounted')
}
})

The code inside the returned function will execute when the component is unmounted, allowing you to perform any necessary cleanup.

Similar to componentWillUnmount, you can specify cleanup logic using this return function.

useEffect() can be called multiple times, which is useful for separating unrelated logic.

To optimize performance, you can tell React to skip executing the function by adding a second parameter—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.

Here’s an example:

1
2
3
4
5
6
useEffect(
() => {
console.log(`Hi ${name}, you clicked ${count} times`)
},
[name, count]
)

Furthermore, you can instruct React to execute the side effect only once, during mount time, by passing an empty array:

1
2
3
useEffect(() => {
console.log('Component mounted')
}, [])

This technique is often used and is quite handy.

For a live example of using the useEffect hook, you can check out the following CodePen: React Hooks example #3 side effects by Flavio Copes.

Tags: React hook, useEffect, side effects