Originally posted on my blog
Before React 16.8, we were forced to use the class-based component to have access in component lifecycle. And now with Hooks, we are now able to use functional component for state management, data fetching etc. We can now replace component lifecycle like componentDidMount
, componentDidUpdate
and componentWillUnmount
with useEffect
in our React component.
1. componentDidMount
The componentDidMount()
method runs after the component output has been rendered to the DOM. This is a good place to cause side-effects.
// With ccomponentDidMount()
componentDidMount() {
console.log('Hello World');
}
// with useEffect()
useEffect(() => {
console.log('Hello World');
}, [])
If we don't pass an empty array to useEffect
, it will run on every change. Therefore, we must give as second argument an empty array to mimic the componentDidMount behavior. It tells to React that your effect doesn’t depend on any values from props or state, so it never needs to re-run, useEffect
will run only once after the component is created.
2. componentDidUpdate
The componentDidUpdate()
method is invoked immediately after updating occurs.
// With ccomponentDidUpdate()
componentDidUpdate(prevProps) {
console.log(`Hello World ${prevProps}`);
}
// with useEffect()
useEffect(() => {
console.log('Hello World');
}, [prevProps])
When we pass a value(prevProps
) to the array, it tells to useEffect
to run only if the value change.
3. componentWillUnmount
The componentWillUnmount()
method is called immediately before a component is unmounted and destroyed. It is a good place to do some cleanup works.
// With ccomponentDidUnmount()
componentWillUnmount() {
console.log('Hello World');
}
// with useEffect()
useEffect(() => {
console.log('Hello World');
return () => {
console.log('Do some cleanup');
}
}, [])
By returning an anonymous function with useEffect
, it will run before the component unmounting. And the empty array passed as second argument tells to useEffect
to run when the component will be mounted or unmounted.
Top comments (4)
Nice article! The effect you wrote for the componentDidUpdate example will be also called at mount. You need to use a ref to ensure it isn't called at mount 😄 (This is a detail)
That detail matters a lot. Thanks for your comment
Merci beaucoup pour l'article.je viens de mieux comprendre useEffect
Au plaisir et merci beaucoup de l'avoir lu.