loading...

Cheatsheet to React Lifecycle hooks Part-3

lakshyabatman profile image Lakshya Khera ・2 min read

So, here is the final blog of the series, hope you've learned something out it.

Anyway, links to my previous blogs:

So, let's end with lifecycle hooks in functional components and they're pretty clean and easy to grasp.

To add these lifecycle hooks we'll use useEffect from react package.

import React, {useState, useEffect} from 'react';
Enter fullscreen mode Exit fullscreen mode

Now in our functional component, we can use it this way.

useEffect(() => {
 console.log("Use effect go brrr!");
});
Enter fullscreen mode Exit fullscreen mode

It's pretty easy to understand, that the callback function will be executed when the hook is trigged.
But when will it be executed?
In this case, in all events.

How we can utilise to trigger on specific change ?

In the previous example, if I add a second argument of array type then the hook will be triggered whenever the element placed in that array is changed and this element can be props, state or anything.

useEffect(() => {
 console.log("Use effect go brrr!");
}, [props.a, state.b]);
Enter fullscreen mode Exit fullscreen mode

Here, the hook will only be triggered whenever props.a and state.b updates.

So, what about when we want the hook to trigger on mounting only

We can place an empty array in the second argument and this will make sure the hook only runs on mounting.
This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

useEffect(() => {
 console.log("Use effect go brrr!");
}, []);
Enter fullscreen mode Exit fullscreen mode

Okay! We can do this, don't give up!

What about cleanup or when the component unmounts

So, in our effect, we can return a function and it'll run after the first execution of the effect and before every other render cycle.

Yeah, it is what it is.

But we can utilise it in a lot of ways! Seriously!
In our previous explanation, this return function will be called before useEffect method except the first when useEffect is called, which means we can use it for cleanup work. ¯\_(ツ)_/¯

But what about the case when [] is passed in second argument, which means in this case the return method will be executed when the component unmounts!

So, this is the end! I'm tired now but yeah don't let my hard work fade away. Make sure you read the docs and try things out! <3
Happy coding!

Discussion

pic
Editor guide
Collapse
davidcoroian profile image
David

Hey, the links you posted to the previous posts (part 1 & 2) seem to link to this post instead

Collapse
lakshyabatman profile image
Lakshya Khera Author

Oh thanks for letting me know, I've fixed it.