React useEffect() hook tutorial for begginers
Tags: react, javascript, webdev, beginners
Published: 2021-02-23 11:35:24

<p>In this post I will show you the usage of useEffect hook. Which is really really important if you are a reactjs dev. So if you are interested to learn it, continue reading....</p>

<p>Before using this hook, we have to import it from react.</p>
```react
import React, {useEffect} from 'react';
```
<p>So what is the use of this hook and how do we use it? useEffect Hook lets you perform side effects in functional components. It performs an action once the page loads for the first time. Example:- Fetching requests, manipulating DOM directly, using timer functions like setTimeout(), and more. The component rendering and side-effect logic are independent. So it would be a mistake to perform side-effects directly in the body of the component. Let's try to use this hook.........</p>
```react
useEffect(() => {
    // put your code here
  }, dependencies)
```
<p>This is the syntax of useEffect hook. It takes a callback function and an argument which is called dependencies. Dependencies is an optional array of dependencies. useEffect() executes callback only once the page loads...</p>
```javascript
useEffect(() => {
    console.log("HI there");
  });
```
<p>In this code, I don't have any dependencies. It has printed - 'hi there' for a single time after the page has been loaded.</p>
<br />

<h1>The dependencies of useEffect()</h1>
<p>Dependencies are some arguments of useEffect hook. So with this arguments, you can control the side effects. To do that, we pass our dependencies under an array. But at first let's try with an empty array and let's see what happens.</p>
```react
useEffect(() => {
    console.log("HI there");
  }, []);
```
<p>It has printed - 'hi there' for a single time after the page has been loaded.</p>
<p>Now look at the code below.</p>
```react
import React, { useEffect, useState } from "react";

const App = () => {
  const [state, setState] = useState(0);
  useEffect(() => {
    console.log("HI there");
  }, [state]);
  return (
    <>
      <button
        onClick={() => {
          setState(state + 1);
        }}
      >
        Click Me
      </button>
    </>
  );
};

export default App;

```
<p>Here in this code, I just have a button. Which will increment the current value of our state. And in useEffect I have put the state variable as a dependency of the hook. So what will be happened here?</p>
<p>This will execute the code under the callback every time the value of our state variable changes. You can perform any action here. And you can also perform multiple actions.. no problems or error's will be seen.</p>
<br />

<h1>Fething Data</h1>
<p>Now I will show you how fetch some data's from an api using useEffect hook.</p>
```react
import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState("");
  const fetchData = async () => {
    const api = await fetch("https://jsonplaceholder.typicode.com/todos/");
    setData(await api.json());
  };
  console.log(data);
  useEffect(() => {
    fetchData();
  }, [data]);
  return <>
    <h1>I am fethcing some fake data's</h1>
</>;
};

export default App;

```
<p>So let me explain you. I have a fake api which is giving me some fake data's. Now to fetch them in a React way, you have to use this useEffect hook.</p>
<p>And if you pass an async function as a callback under useEffect, it's 
not gonna return you anything. So I have passed a function there. Which is an asyncronous function and I am fetching the data from the api. Then I am storing the api data under my state variable and printing it in my console. That's all. Hope you are familiar with fetch api 😅</p>
![Ratuloss-react-useEffect-hook-for-begginers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hyuh5t8tbkvj55snxe2t.PNG)
<br />

<h1>Clean up function</h1>
<p>Cleanup works in this following ways:</p>
<p>1. After initial rendering, useEffect() invokes the callback having the side-effect. cleanup function is not invoked.</p>
<p>2. On later renderings, before invoking the next side-effect callback, useEffect() invokes the cleanup function from the previous side-effect execution (to clean up everything after the previous side-effect), then runs the current side-effect.</p>
<p>3. Finally, after unmounting the component, useEffect() invokes the cleanup function from the latest side-effect.</p>
<p>Let me show you an example.</p>

```react
import React, { useEffect, useState } from "react";

const App = () => {
  const [state, setState] = useState(window.innerWidth);
  console.log(state);
  const resizeD = () => {
    setState(window.innerWidth);
  };
  useEffect(() => {
    window.addEventListener("resize", resizeD);
  }, [state]);
  return (
    <>
      <h1>{state}</h1>
    </>
  );
};

export default App;

```
<p>Here I have a simple piece of code. Which giving me a live preview of my screen size. I have a useEffect here, which will be called every time when my variable value changes. And I am rendering the value of our variable under h1. So in this case, the state variable is changing every time when we resize the window. And if you print the value of the state variable in the console, you will see it is printing too many ( every time you resize the window ) times but it not removing anything. Which is not a good stuff. So in this case you application may crashed or the client may have a bad experience. So we use cleanup functions in useEffect. It immidietly removes the value when another new value exists for the same variable.</p>
<p>Before adding cleanup function - </p>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjqki6x7ukjeon3bf0f7.PNG)
<p>Now let's add a cleanup function-</p>
```react
    return () => {
      window.removeEventListener("resize", resizeD);
      console.log("removed");
    };
```
<p>That's all now the whole code will be look like that -> </p>
```react
import React, { useEffect, useState } from "react";

const App = () => {
  const [state, setState] = useState(window.innerWidth);
  console.log(state);
  const resizeD = () => {
    setState(window.innerWidth);
  };
  useEffect(() => {
    window.addEventListener("resize", resizeD);
    return () => {
      window.removeEventListener("resize", resizeD);
      console.log("removed");
    };
  }, [state]);
  return (
    <>
      <h1>{state}</h1>
    </>
  );
};

export default App;

```
<p>After adding a cleanup function -> </p>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qoq8hihhqv1xg17szijd.PNG)
<p>Did you see that now it is removing the previous data, when any new data exits for our variable. So this clean up function can increase you application performance. If there is any other use of this clean up function, please let me know.</p>
<br />

<p>So That's all I know about useEffect hook. Hope you enjoyed that. If you have any issue regarding that post, please let know. And make sure you follow me to receive all the informational posts just like that one.</p>
<h1>:)</h1>