useEffect
is a React hook used for managing the side effects of the component. By using this Hook, you tell React that your component needs to do something after render. It removes the need for componentDidMount
, componentDidUpdateand
and componentWillUnmount
.
useEffect(callback, [dependencies]);
useEffect()
hook accepts 2 arguments: callback and dependencies. The side effects are written inside the callback function. The dependencies argument lets you control when the side-effect runs. There can be three conditions for providing the dependencies:
The side-effect runs after every rendering.
import React , {useState , useEffect} from 'react'
function Example() {
const [count , setCount ] = useState(0);
useEffect(()=>{
console.log('click')
}) // no dependencies provided
return (
<div>
<button onClick={()=>setCount(count+1)}>click me !</button>
<span>you clicked {count} times</span>
</div>
)
}
export default Example
Output:
Here, we can see that the function inside useEffect()
,console.log("click")
runs every time we click on the button.
[]
The side-effect runs once after the initial rendering.
useEffect(()=>{
console.log('click')
} ,[]) // empty dependencies provided
Output:
Here, we can see that the function inside useEffect()
runs only once no matter how many times we click on the button.
[prop1, prop2, state1, state2]
The side-effect runs once after initial rendering and after every rendering ONLY IF prop
or state
changes.
useEffect(()=>{
console.log('click')
}, [count]) // state value provided
Output:
Here, we can see that the function inside useEffect()
runs once after initial rendering and after every time we press on the button.