How to use useEffet() for Lifecycle Method
So React Hook is pretty popular these days. useState() allows function component to store state. Now many developer who just shifting to function component from class component may face trouble finding how to write componentDidMount or ComponentDidUpdate etc. This blog will help you understand this. If you want to know more please check Dan’s Blog or React Official Document
TLDR:
read conclusion
Lets focus on these methods
- ComponentDidMount
- ComponentDidUpdate
- ComponentWillUnmount
You can use all these lifecycle methods in one useEffect() function.
componentDidMount:
So let’s start with componentDidMount, in useEffect function you can pass a function and a array
class TestFunction extends React.Component {
componentDidMount() {
console.log('I am mounted!');
}
render() {
return <div>Render Text</div>;
}
}
Turn this into,
function TestFunction() {
useEffect(() => console.log('mounted'), []);
return <div>Render Text</div>;
}
Notice this useEffect part,
useEffect(() => console.log('mounted'), []);
or
useEffect(fn, []);
so for componentDidMount just pass a empty array. You might ask how its working? Hold your coffee, I will discuss in the later section of this blog.
componentDidUpdate:
for componentDidupdate just don’t pass any variable after you give function in useEffect parameter.
useEffect(() => console.log('mounted or updated'));
or
useEffect(fn);
if will fire every time render function called.
componentWillUnmount:
for componentWillUnmount this is more like componentDidMount but inside your function (fn) return another function which will behave as componentWillUnmount.
useEffect(() => {
return () => {
console.log('will unmount');
}
}, []);
or
useEffect(fn(()=>console.log('will unmount')),[]);
Call useEffect for specific state change:
one of the benefit of useEffect is you can trigger this function iff one specific state is changed. for example,
in these case when user Change useEffect will trigger.
Conclusion:
To wrap up things, Remember these things,
- pass a function and empty array inside useEffect for componentDidMount,
- pass a function with specific state inside the array will call useEffect function when that specific state changes,
- pass a function without any array for componentDidUpdate and componentDidMount both.
- pass a function and empty array, return another function inside the initial function that will behave as componentWillUnmount.
If you are thinking I referred function component instead of functional component see this thread ;)
If this is very basic for you this blog is not for you.
I recommend you read THIS :)
THANKS, Find me here,