简体   繁体   中英

React 'useEffect' hook replaces how many lifecycle methods?

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 :

  • runs after every render, unless you provide a dependency array.
  • If you provide in a dependency array, it runs on first render, and then whenever the dependencies change.

The function your return from your useEffect function:

  • Is run before each render (except the very first) unless you provide a dependency array.
  • If you provide a dependency array, it is run before a render where the dependencies have changed, or the component unmounts.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM