Reputation: 688
I want to know when is the useEffect
hook clean up function get called in react, Does it get called on dependency change or it get called when component is unmounted.
For example in my component if i have useEffect
useEffect(()=>{
return ()=>{
//clean up function code
} //clean up function
},[dependency])
will the clean up function get's called on dependency
change or it will get called when the component gets unmounted.
Upvotes: 5
Views: 1323
Reputation: 1483
Just adding on @Vivek Doshi answer. useEffect is synonym to componentDidMount
, componentDidUpdate
, and componentWillUnmount
combined. The effect is run on first render, all subsequent re-renders (unless conditions provided).
Cleanup is run when component unmounts.
To avoid unexpected bugs, react will clear the effect before running new effect. You can play around and grasp the concept with this sandbox
Upvotes: 0
Reputation: 58573
It will clean up on both case (unmount and on change of dependency) as you have passed dependency
:
When exactly does React clean up an effect? Ref
React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
Upvotes: 4