How to use useEffect React Hook

Today we will show you how to use useEffect React Hook. The useEffect is the one of the important hooks that is providing an access to the lifecycle in the functional components.

It is a close replacement for componentDidMount, componentDidUpdate and componentWillUnmount.

In this article, we’ll take several examples to check the lifecycle in the functional component.

useEffect React Hook

  1. Example of the useEffect as componentDidMount
  2. Use the useEffect as componentDidMount and componentDidUpdate
  3. Conditionally run the code using useEffect
  4. Example of the useEffect as componentWillUnmount

1. Example of the useEffect as componentDidMount

Here, we will take a simple example to change the title of the document using useEffect. So first we will show you the same example using the class component.

ClassExample.js

Let’s convert the above code using useEffect.

HookExample.js

You have to pass an empty array ([ ]) to perform the useEffect as componentDidMount.

2. Use the useEffect as componentDidMount and componentDidUpdate

Let’s take another example to use the useEffect as componentDidMount and componentDidUpdate. So here we will use the above example to update the document title with useState hook.

ClassExample.js

Now let’s create the same example using useEffect.

HookExample.js

If you remove the second argument of the useEffect then it will act as componentDidMount and componentDidUpdate.

3. Conditionally run the code using useEffect

If you want to conditionally execute the code using useEffect then we have to use the second argument of the useEffect. For demonstration, we will use an input field for name and button for counter to manage the state variable.

ClassExample.js

Here we have used the prevState in the componentDidUpdate to avoid the unnecessary rendering. Let’s mimic the same example using the useEffect.

HookExample.js

Pass the variable (Like [counter]) in the array to manage the conditional execution. You can pass the multiple variables in an array such as [var1, var2, var3] to re-run the effect even if just one of them is different.

4. Example of the useEffect as componentWillUnmount

Let’s use the addEventListener in componentDidMount to capture the mouse coordinates and use the removeEventListener in componentWillUnmount for cleanup.

ClassExample.js

Now we will convert the above example in Hooks. If your effect returns a function from useEffect Hook, React will run it when it is time to clean up.

HookExample.js

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *