How many lifecycle methods can be replaced by React useEffect
?
I found an article on the useEffect
hook that claims that it can replace only three, ie componentDidMount
, componentDidUpdate
and componentWillUnmount
.
What about others?
That is actually all. useEffect() is called once component is mounted and than on every state update. If you want to use it as componentWillUnmout you have to return a cleanup function like so
useEffect(() => {
//something you want to do
return () => console.log('cleanup is running');
});
Nope that's pretty much it, though it comes close to componentWillUpdate
when you return a function and dont pass dependencies (it just doesn't run before the first render)
It's a really simple hook when you think about. The rules are pretty straightforward:
The function you pass to useEffect
:
The function your return from your useEffect
function:
It's probably best not to think about lifecycle events it replaces. Instead think about these 4 rules and how get them to run your functions when you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.