Get Up And Running With The useEffect Hook.
Tags: webdev, react, javascript, programming
Published: 2022-06-21 08:46:12

**Hooks** are new features incorporated into React 16.8. and the newer versions. They basically help you use React features without writing a class.

**In this guide, we are going to cover why this hook exists and how to use it in React.**

If you started your React journey before version 16.8, then you have to unlearn lifecycle methods and instead think in effects.

The useEffect hook lets us express different kinds of **side effects** after a component renders. In case you are wondering what side effects are, relax, you will understand in a second.

Side effects are unpredictable actions performed with the "outside world."_<u> Data fetching, setting up a subscription, and manually changing the DOM in React components</u>_ are all examples of side effects. Regardless of knowing what this term means, you have most likely used it.

There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do.

**Side Effects Without Cleanup**
Network requests, manual DOM mutations, and logging are common examples of effects that don’t require a cleanup. We can run them and immediately forget about them.

**Side Effect With Cleanup**
Some effects require cleanup **to reduce memory leaks.**
Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.
This is done by **_including a return function_** at the end of the useEffect Hook.

![cleanup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbckjhrwatjfwi97cst2.png)

useEffect is a tool that lets us interact with the external world but does not affect the rendering or performance of the component that it's in. React enables multiple useEffect instances inside a React functional component. The code can be broken down into multiple Hooks containing logically related code in a single function.

By using this Hook, 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.

It is a combination of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class-based components.


##**Why useEffect is defined inside a component?**

“useEffect” function is defined inside the component so that the variables and the functions defined inside the components can be accessed directly. If you are familiar with closures in JavaScript, you will probably be having an "aha!" moment now. And if you don't, it is not a problem. 

**Closures** are functions that are nested in other functions and simply allows variables outside of the scope of a function to be accessed. It takes advantage of the concept of Closure to provide access to the local functions and variables defined inside a function.
 
##**How to use the useEffect hook**

1. We import useEffect from "react"
2. We call it above the returned JSX in our component
3. We pass it **<u>two arguments</u>**: a function and an array


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

function Counter() {
  const [count, setCount] = useState(0);
  const [calculation, setCalculation] = useState(0);

  useEffect(() => {
    setCalculation(() => count * 2);
    console.log(calculation);
  }, [count]); // <- add the count variable here

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <p>Calculation: {calculation}</p>
    </>
  );
}
```
The function passed to useEffect is a **callback function** which will be called after the component DOM renders. The side Effects are performed inside this function.

The second argument is an array, called the dependencies array. This array includes all of the values the side effect relies on. What this array will do is it will check and see if a value has changed between renders. If so, it will execute our use effect function again. We can optionally pass dependencies to useEffect in this array.

**1. No dependency passed:**
useEffect(() => {
  //Runs on every render
});

**2. An empty array:**
useEffect(() => {
  //Runs only on the first render
}, []);

**3. State values passed into array:**
useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [state]);


## **Summary**
useEffect is a tool that lets us interact with the external world but does not affect the rendering or performance of the component that it's in.
By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed, and call it later after performing the DOM updates.

It is a combination of componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class-based components.
We pass **<u>two arguments</u>**: a function and an array into a useEffect hook.