useEffect React hook, how to use
By Flavio
Published · Updated
Tagged: React
Learn how to use the useEffect React hook to run side effects after render, control runs with a dependency array, and clean up with a returned function.
Check out my React hooks introduction first, if you’re new to them.
One React hook I use a lot is useEffect.
import React, { useEffect } from 'react'
The useEffect function runs when the component is first rendered, and on every subsequent re-render/update.
React first updates the DOM, then calls the function passed to useEffect().
Example:
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>
)
}
TIP: if you’re an old-time React dev and you’re used to
componentDidMount,componentWillUnmountandcomponentDidUpdateevents, this replaces those.
You can optionally return a function from the function you pass to useEffect():
useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`)
return () => {
console.log(`Unmounted`)
}
})
The code included in that function you return is the cleanup. React runs it when the component is unmounted, and also before running the effect again after a re-render, so the previous effect gets cleaned up first.
You can use this for any “cleanup” you need to do.
For old timers, this covers
componentWillUnmount, and more
useEffect() can be called multiple times, which is nice to separate unrelated logic.
Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip executing the function, for performance purposes, by adding a second parameter which is an array that contains the dependencies of the effect: every prop, state variable or value derived from them that the effect uses.
React will only re-run the side effect if one of the items in this array changes.
useEffect(
() => {
console.log(`Hi ${name} you clicked ${count} times`)
},
[name, count]
)
Similarly you can tell React to only execute the side effect once (at mount time), by passing an empty array:
useEffect(() => {
console.log(`Component mounted`)
}, [])
This ☝️ is something I use all the time.
In development, with Strict Mode on, React runs setup, cleanup and setup again when the component mounts, to help you spot effects that don’t clean up properly. In production it runs once. More in why does useEffect run two times?
How React compares the dependencies
React compares each item in the dependency array with its value from the previous render using Object.is. For numbers, strings and booleans that’s what you expect: 5 is equal to 5.
Objects, arrays and functions are compared by reference. If you create one in the body of the component, you get a brand new one on every render, so the effect runs every time:
const Chat = ({ roomId }) => {
const options = { roomId } // new object on every render
useEffect(() => {
const connection = createConnection(options)
connection.connect()
return () => connection.disconnect()
}, [options]) // 🚩 always "changed"
// ...
}
The fix is to create the object inside the effect and depend on the plain values instead:
useEffect(() => {
const options = { roomId }
const connection = createConnection(options)
connection.connect()
return () => connection.disconnect()
}, [roomId]) // ✅ only re-runs when roomId changes
Fetching data in useEffect
You can’t pass an async function to useEffect(). An async function returns a promise, and React expects your effect to return nothing or a cleanup function.
Define the async function inside the effect and call it:
const [user, setUser] = useState(null)
useEffect(() => {
let ignore = false
async function load() {
const response = await fetch(`/api/users/${userId}`)
const data = await response.json()
if (!ignore) {
setUser(data)
}
}
load()
return () => {
ignore = true
}
}, [userId])
The ignore flag protects you from a race condition. If userId changes quickly, two requests are in flight and the responses can come back in any order. The cleanup of the old effect sets ignore to true, so the old response is thrown away and only the latest one updates the state.
In a real app, consider your framework’s data fetching, or a library like TanStack Query or SWR, which cache results and handle these race conditions for you. With React 19 you can also use use() with Suspense.
Common pitfalls
An infinite loop. If the effect sets a state variable that is also in its dependency array, and the new value is always different (like a new object or array), the effect runs, sets the state, re-renders, and runs again forever. The same happens if you set state in an effect with no dependency array at all.
An interval that keeps restarting. This works, but it clears and creates the interval every time count changes:
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1)
}, 1000)
return () => clearInterval(id)
}, [count])
Pass an updater function to the setter instead. Then the effect doesn’t read count at all, and it can run once:
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1)
}, 1000)
return () => clearInterval(id)
}, [])
Missing dependencies. Don’t leave out a value the effect uses just to make it run less often. The react-hooks/exhaustive-deps ESLint rule warns you about this with a message like React Hook useEffect has missing dependencies. When it complains, change the code so the effect needs fewer values, like in the two examples above, instead of silencing the rule.
Using an effect when you don’t need one. If you only compute a value from props or state, like a filtered list or a full name, compute it while rendering. Putting it in an effect plus a state variable causes an extra render and shows stale data for a moment. Effects are for syncing with something outside React: the network, timers, the DOM, a subscription.
Effects run only in the browser
Effects don’t run during server rendering. If your component is also rendered on the server, code that touches window, document or localStorage is safe inside useEffect(), because it only runs in the browser.
React usually lets the browser paint the screen before it runs your effect. If your effect measures the DOM and changes the layout, and you see a flicker, use useLayoutEffect() instead. It has the same API and runs before the browser paints.
If you’re ever unsure whether useEffect is the hook you need, try my free React hook chooser.
Example on Codepen:
See the Pen React Hooks example #3 side effects by Flavio Copes (@flaviocopes) on CodePen.
Want me to talk about your product? You can sponsor this site.