Everything you need to know about useEffect hook of React

A beginner's guide

ThreadđŸ§”đŸ‘‡
If you're familiar with class components then you might know that we have various lifecycle methods but in functional components, we don't have any lifecycle methods.

Instead we have a powerful hook called useEffectđŸ’Ș
By using useEffect, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our “effect”), and call it later after performing the DOM updates

So let's start by understanding the syntax first👇
useEffect take two parameters, first is a function and second is an array.

The function inside the useEffect will run every single time component re-render.

Consider this piece of code and check the output in next tweet
As you can see in the output the function is executed every single time my component re-render👇
But let's say if I add some dependency in the array and pass the array as second parameter then useEffect will only run when the value of dependency array change. 

For example let me modify the code little bit so that you can understand it better
As you can when I click on the re-render button, our useEffect run this is because I have passed render state inside dependency array👇
📌 Here's an important thing to note is that if you pass an empty array then it will only run on once. 
No matter how many times you render your component, the useEffect will run only once because the value of empty array never going to change
In useEffect we can also perform clean up

If we return a function within the method, this function perform basically a clean up of what we did last time.
For example, consider this piece of code

useEffect(() => {

    console.log({ render });

    return () => {
      console.log("I'm cleanup function");
    };
  }, [render]);

Everytime I click the button, first our useEffect perform clean up then run the effect function
So far we have discussed the basics of useEffect. 

Let's build something useful using it. We will be using useEffect for fetching some COVID data
We will print total number of confirmed COVID cases of a specific country enter by user in the input field.

On the basis of the value entered by user we will store that in "country" and change that value in our API link
- Make an input field  
- on form submit, store the input value in "country" 

Print the confirmed cases on screen as simple as thatđŸ€©

check the entire code👇
Great! I hope that's pretty much it for useEffect. 

I hope you get a basic overview of it. Did I miss something? Feel free to add your suggestions down below😉

And I'll catch you with a next thread❀
You can follow @Prathkum.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.