Dive deep into useEffect hook.

Prerequisite :-
a.) Basic understanding of functional component.
b.) Must have worked with useState hook.
This blog will help you to know more about the useEffect hook and get a very good understanding of how the useEffect hook actually works.
We will also compare that what we actually used in place of hooks when we were dealing with class components.
SO LETS START :-
What is useEffect hook ?
It helps you to do side effects in functional components.
Whats the reason we use useEffect hook ?
If you have worked with class components you must have performed the side effects like :-
a.) Fetching data from an API
b.) Updating DOM
Example 1.
Now here is a piece of code if you want to update the document title when the user clicks the counter (using class components).

Explanation of this code :-
componentDidMount function helps us to set the document title to the initial value of the count state when the component loads on the initial render.
componentDidUpdate function :- And when the user clicks the counter the document title updates using this function. And an if condition to have a check on the previous value and the current value of the count. If the current value of the count changes then only the document title gets updated.
Now here we have to write the same piece of code twice even if we have to execute the same statement.
useEffect hook :-
So here we can use the useEffect hook in our functional component.

Explanation of this code :-
Whenever we specify a useEffect hook we are basically requesting the react to execute the function that is passed as an argument everytime the component renders. It runs both after the first render and after every update.
useEffect hook will run after every render. So to avoid that we run the useEffect hook only on some conditions.
So for conditionally executing an effect we pass a second parameter and the second parameter is an array and in this array we define props or state (here we have a count state) .
Here we want to execute the effect whenever the count variable changes.
So we pass the count in the array.
Example 2.
Making an API call for fetching the list of messages .
a. )

Here initially when the component renders we will have a list of messages. This effect will only run once as we pass an empty array as second parameter to the function.
b.) Now if we want to fetch a message with a particular id. And whenever we change the id the respective message should change accordingly.

Here passing the id in the array as a parameter will help to run the effect whenever we change the id.
Thanks for reading the blog. Make sure to give a clap.