DEV Community

Replace lifecycle with hooks in React

Trent Yang on January 06, 2019

If you have ever used React, you should be familiar with power of React lifecycles. The upcoming React hooks are about to change the way we handl...
Collapse
 
avxkim profile image
Alexander Kim

If you use useEffect with empty deps array, ESLint would throw an error, that you have to add all dependencies, or omit deps array at all. So, it's not a replacement for componentdidmount lifecycle. What do you use yourself, when you need to do something, only when your component is mounted?

Collapse
 
svgpubs profile image
svgpubs

I created an account just to like your comment. I am stuck because my useEffect hook relies on local state. Since I need to add local state in the dependency array for the function to work, I cannot use it as a stand-in for componentDidUnmount.

Where is the onUnmount hook?

Collapse
 
arnabsen1729 profile image
Arnab Sen

Take a look at this thread once: github.com/facebook/react/issues/1... Might be helpful

Collapse
 
mujaddadi profile image
Taha Hassan Mujaddadi

That's problem of ESlint. You can easily change the rule by the way.

Collapse
 
avxkim profile image
Alexander Kim

Of course you can, but it's not recommended.

Collapse
 
mujaddadi profile image
Taha Hassan Mujaddadi

Thank you for the article. Although I really like Hooks but the life cycle methods in Classes, properly explains what their use is for. Such as componentDidMount. With hooks by using above technique, it doesn't explain much since there are just small differences between them.

Collapse
 
djlechuck profile image
DjLeChuck

I just created an account to thank you! Nice sheatcheet to have! :)

Collapse
 
enthusiastio profile image
En

So how exactly can you perform an action once the component is mounted in the functional component if it needs a reference to dependencies. Say I have to reference a dispatch method

useEffect(() => {
dispatch({
type: "COMPONENT_INITIALIZED",
payload: { },
});
}, [dispatch]);

I get COMPONENT_INITIALIZED on every render because dispatch is different.

Collapse
 
esr360 profile image
Edmund

"Mimicing only componentDidUpdate can be a discussion of another post." - I would love to read this post :)

Collapse
 
derviselimovic profile image
Dervis Selimovic

Great post !

Have one question tho - what is the goto approach when working with canvases ? (useEffect or useLayoutEffect to get the id e.g

Collapse
 
trentyang profile image
Trent Yang
Collapse
 
anthwinter profile image
Anth Winter

This was a great resource. Thanks for writing!

Collapse
 
marisolh profile image
MarisolH

Thank you!! <-- *I just created my account just for that!

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
trentyang profile image
Trent Yang