DEV Community

Cover image for React: useEffect explained with lifecycle methods

React: useEffect explained with lifecycle methods

Adrian Bece on August 05, 2019

React's useEffect hook combines componentDidMount, componentDidUpdate and componentWillUnmount lifecycle methods. This is very useful for the follo...
Collapse
 
oathkeeper profile image
Divyesh Parmar

Is there a way to implement other Life Cycle Methods e.g., shouldComponentUpdate, which I guess mostly people use with React.PureComponent or that is what I have heard and learnt in interviews.

There is also other way to do it. I guess by using React.memo() function so how can we do that with functional component?

Collapse
 
lamhieu profile image
Hieu Lam

your post is simple but very nice and easy understand about useEffect

Collapse
 
guico33 profile image
guico33 • Edited

Small typo in the last code snippet. I believe you meant componentDidMount rather than componentWillMount in the first comment.

Also equivalent instead of eqivalent.

Collapse
 
adrianbdesigns profile image
Adrian Bece

Good catch. Thank you, I've fixed it now.

Collapse
 
guico33 profile image
guico33 • Edited

In addition to my previous comment, it is incorrect to say the dependency array doesn't affect the cleanup fn returned by the callback.

It is equivalent to componentDidUnmount if an empty array is passed, otherwise it will run whenever a dep changes, after the component has rendered with new props.

Thread Thread
 
adrianbdesigns profile image
Adrian Bece

Double checked with docs, you're right. I've fixed the post. Thank you again.

Collapse
 
2ezpz2plzme profile image
Steven Liao

I believe useLayoutEffect would be more accurate here.

Collapse
 
adrianbdesigns profile image
Adrian Bece

It depends on the use-case. UseEffect is generally more preferable.

Collapse
 
iamshubhajit profile image
Shubhajit Halder

How do I use componentWillMount() in useeffect?

I was asked this today in my interview. I had no answer.

Please let me know

Collapse
 
oathkeeper profile image
Divyesh Parmar

ahh okay thank you :)

Thread Thread
 
kelahkelah profile image
KelahKelah

I love that this article was simple and easy to understand! Thanks