How to Use the useEffect Hook in React
Running side effects in function components with useEffect.
When building React components you will often need to do something after the
component renders, like fetch data, update the page title or start a timer. In a
class component that meant componentDidMount and componentDidUpdate. With
hooks, which landed in React 16.8 last month, function components can do it with
useEffect.
useEffect runs your function after React has rendered the component to the
screen.
Basic Usage of useEffect
Import useEffect from React and pass it a function. Here we update the
document title every time the count changes:
import React, { useState, useEffect } from "react"function Counter() {const [count, setCount] = useState(0)useEffect(() => {document.title = `You clicked ${count} times`})return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>}
Without a second argument, the effect runs after every render.
The Dependency Array
Most of the time you don't want your effect to run on every render. The second argument is an array of values the effect depends on. React only runs the effect again when one of them changes:
useEffect(() => {document.title = `You clicked ${count} times`}, [count]) // only runs when count changes
Pass an empty array to run an effect only once, after the first render. This is
the hooks version of componentDidMount:
useEffect(() => {console.log("mounted")}, [])
Important! Include every prop and state value your effect uses in the dependency array. If you leave one out your effect will use a stale value.
Cleaning Up an Effect
Some effects need to be undone, like event listeners and timers. Return a function from your effect and React will call it before the component is removed, and before the effect runs again:
function WindowWidth() {const [width, setWidth] = useState(window.innerWidth)useEffect(() => {const handleResize = () => setWidth(window.innerWidth)window.addEventListener("resize", handleResize)return () => {window.removeEventListener("resize", handleResize)}}, [])return <p>The window is {width}px wide</p>}
The listener gets added once when the component mounts, and the cleanup function
removes it when the component unmounts. This is the hooks version of
componentWillUnmount.
Using More Than One Effect
You can call useEffect as many times as you need. Splitting unrelated logic
into separate effects keeps each one small and easy to follow:
useEffect(() => {document.title = `You clicked ${count} times`}, [count])useEffect(() => {const id = setInterval(() => console.log("tick"), 1000)return () => clearInterval(id)}, [])
With class components this logic would be spread across three different
lifecycle methods. With useEffect the code for each job stays together.
Have some feedback on this post? .