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