useEffect - React Hooks Series
Tags: react, javascript, beginners, webdev
Published: 2021-06-26 04:24:25

Welcome back to the series of **React Hooks**. In part one of the series, I wrote about the useEffect react hook.

**Series path**

- [useState](https://pratapsharma.io/use-state-react-hook)
- useEffect

## What is `useEffect` hook?

The `useEffect hook` lets you perform side effects in functional components.

### Few examples of side effects

- Data fetching
- Setting up a subscription
- Manually changing the DOM in React

If you are familiar with `React class lifecycle` methods, you can think of `useEffect hook` as `componentDidMount`, `componentDidUpdate` and `componentWillUnmount` combined.

## What does `useEffect` hook do?

By using this `hook`, you let React know that your component needs to perform something **after rendering** of the component. React will remember the function which you passed and react call it **after performing the DOM updates**.

In this _effect_ we can do many things like setting document title, fetch some data from an API, setting event listeners.

## Does useEffect run after every re-render?

Yes! By default, the effect runs both after the first render and after every update of the component. Rather than thinking in terms of **mounting** and **updating**, you might find it simpler to think that **effects** happen **after render**. React **guarantees** the DOM has been updated by the time it runs the effects.

## Example

Let's change the document title for better understanding.

### Using class component

```jsx
import React from "react";

class ExampleComponent {
  //After rendering
  componentDidMount() {
    document.title = "Updating the title in componentDidMount";
  }

  //After updating
  componentDidUpdate() {
    document.title = "Updating the title in componentDidUpdate";
  }

  render() {
    return <div>Setting the title</div>;
  }
}

export default ExampleComponent;
```

### Using functional component

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

const ExampleComponent = () => {
  useEffect(() => {
    document.title = "Setting title using useEffect";
  });

  return <div>Setting the title using useEffect hook</div>;
};
```

In **function component**, you have to define one **useEffect** function instead of **componentDidMount** and **componentDidUpdate**.

## Getting deeper

Now we know what **useEffect** is. Let us try to understand it deeper. **useEffect** function accepts two-parameter. i) A function which gets called on every update/re-rendering. ii) An array of dependencies value on which the function has to get called.

<strong>1.</strong> The useEffect below will always get called on rendering and updating of the component.

```js
useEffect(() => {
  console.log(
    "I will be called each time the component renders and re-renders"
  );
});
```

<strong>2.</strong> The useEffect below will get called only once. i.e. the first time it renders. It is equivalent to **componentDidMount**. The second parameter `[]` is called the dependencies array. An empty array means no dependency.

```js
useEffect(() => {
  console.log("I will be called only once when the component is mounted");
}, []);
```

<strong>3.</strong> The useEffect below will get called each time the value of **name** is changed. It is like **componentDidUpdate**.

```js
useEffect(() => {
  console.log("I will be called first when the component is mounted and each time the name is changing");
}, [name]);
```

<strong>4.</strong> If we want to do any clean-ups before the component is unmounted.

```js
useEffect(() => {
  // some tasks

  return () => {
    console.log("I do cleanups");
    console.log(
      "will first run on component mount then, will run before useEffect and lastly before unmounting"
    );
  };
});
```

## Wrapping up

I want to thank you for going through the part two of my React Hooks series, in case you missed part one please check it out here(hyperlink)

If you have any questions, comments, corrections I would look forward to it. Thank you for making it this far.

**Series path**

- [useState](https://pratapsharma.io/use-state-react-hook)
- useEffect

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter [here](https://pratap.substack.com).