Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
So far you have seen how to manage state with the useState hook. Another important hook is useEffect.
useEffect lets you run code when the component mounts (first render) and when it re-renders.
Pass a function to useEffect; React runs it after the component mounts and after each update. React updates the DOM first, then runs the effect.
Here is an example:
import { useEffect, useState } from 'react'
const CounterWithNameAndSideEffect = () => {
const [count, setCount] = useState(0)
useEffect(() => {
console.log(`You clicked ${count} times`)
})
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
By default the effect runs after every render. To control when it runs, pass a second argument: a dependency array. React re-runs the effect only when one of those values changes:
useEffect(() => {
console.log(`Hi ${name} you clicked ${count} times`)
}, [name, count])
Pass an empty array [] to run the effect only on mount:
useEffect(() => {
console.log(`Component mounted`)
}, [])
Note: In React 18, in development mode (not production), the effect runs twice on mount. Do not worry if you see the function called twice instead of once. If this is a problem for your app, the tutorial on how to address it.