React Lifecycle Methods - The Basics
Tags: javascript, react, codenewbie
Published: 2020-08-17 15:14:41

If you're using React then you're likely using Components. Why else would you be using React if you weren't, right? If you're using Components then you'll end up needing at least a little knowledge of how the **Component Lifecycle** operates.

## The Basics

In the [React Docs on Components](https://reactjs.org/docs/react-component.html) they do a great job of laying it all out. I definitely recommend reading it over. _This article_ should provide you a quick overview of the **Lifecycle**, it's most commonly used methods, and how some of the common **Hooks** fit into that lifecycle.

So first, as React was initially based around, and still probably most commonly used at least for now, classes. The _Lifecycle Methods_ are methods of _React Classes_.

We can break these methods up into three categories:

- **Mounting**
- **Updating**
- **Unmounting**

Updating seems self-explanatory, but what does it mean to _mount_ or _unmount_?

## Mounting

When a Component has _mounted_ that means that a couple things have already taken place. 

1. That Component's `constructor()` has been called and finished
2. The Component's `render()` has ran for the first time

**At this point in time specifically** after this Component **for the first time** has been initialized with its `constructor()` and it's first `render()` called **it has mounted**.

It is, in simplest terms, the first time that a Component renders to the screen. _This is where the `componentDidMount()` lifecycle method comes in_.

### `componentDidMount()`

This method is where, as a developer you'd like to make an API call, an initial database query, basically anything that can take some time fetching from a remote source. The Component has already rendered so the User won't be staring at a blank screen while waiting for the data to come back because these are _asynchronous_ tasks.

You can also `setState()` inside of this method and if it's _not_ dependent on an asynchronous task it will fire another `render()`. The good thing is with a synchronous task here the User _will not see the intermediary state_. 

1. `constructor()`
2. `render()`
3. `componentDidMount()`
4. `render()` (If the state was changed in _componentDidMount()_)

## Updating

This one again is pretty self-explanatory. This is when a Componenet has updated. To be more specific, whenever we pass in new props to a Component or if the state within that component has changed the Component _has updated_.

So what happens on an update? Well, a `render()` of course! Followed up by our next lifecycle method `componentDidUpdate()`. 

> Now there is a less used method `shouldComponentUpdate()`, but take a look at the [React Docs on Components](https://reactjs.org/docs/react-component.html) if you want to know more about the usage of that.

### `componentDidUpdate()`

This'll be a quick one. We already know that new props or `setState()` causes a `render()` and then `componentDidUpdate()` will fire.

What do we use it for though?

It's almost exactly the same use as `componentDidMount()`. Network requests are a big use case for this method. You can just the same call `setState()` inside this lifecycle method. 

One catch to using `setState()` inside `componentDidUpdate()` is to be wary of the _infinite loop_. If you **must use `setState()` inside `componenetDidUpdate()`** then you **must also compare props with previous props**. Doing this will prevent that infinite loop.

To clarify here's an example straight from the Docs that we'll add one line to and break down a little bit.

We can tell there's a method on this class Component called `fetchData()` that clearly takes a `userID`. We see that the `userID` is coming from `props`. Okay, nothing crazy.

```jsx
componentDidUpdate(prevProps) {
  if (this.props.userID !== prevProps.userID) {
    const dataObject = this.fetchData(this.props.userID);
    this.setState(dataObject)
  }
}
```

To understand where the problem lies lets layout the lifecycle method calls.

Lets say this component has already went through

- `constructor()`
- `render()`
- `componentDidMount()`

And now in our program the user has performed an action that changes our props. Lets say they entered _their ID into an input_ and now we pass that down as a prop to **this Component**.

- User enters ID into input on a form and submits
- _The props of this component change_ 
  - Which will trigger a `componentDidUpdate()`
- `componentDidUpdate()`
  - Which has a `setState()`
- _The state of this component changes_
  - Which will trigger a `componentDidUpdate()`

**At this moment** if we do not compare the Previous Props to the current Props and _ensure that they are different_ we will fall into that infinite loop because **state is set inside the update**.

- Props change
- `componentDidUpdate()`
- `setState()`
- `componentDidUpdate()`
- `setState()`
- `componentDidUpdate()`
- etc. etc. etc. NOOoooooo, why me!?!

## Unmounting

This will also be quick. The only time this is ran is when the Component is being taken out of the DOM tree altogether and destroyed. And it has only one method: `componentWillUnmount()`.

Now this is one personally I haven't used yet. The Docs put it pretty succinctly and in a way that _I understand_ but haven't in my little React experience _needed quite yet_.

> Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in `componentDidMount()`.

Don't bother using `setState()` in this method as the Component is removed and destroyed immediately after whatever functionality you have inside this function.

No amount of standing outside it's house with a boombox jamming "In Your Eyes" by Peter Gabriel will bring it back.

![John Cusack holding boombox in 'Say Anything' movie](https://dev-to-uploads.s3.amazonaws.com/i/tktajrv4co8fkcyyoh8o.jpg)


---

Definitely still go to the [React Docs on Components](https://reactjs.org/docs/react-component.html) and read up. They have great examples, they show the less used (but still useful) lifecycle methods, and they also include the Error Boundary ones which I did not for simplicity.

**My biggest recommendation for understanding these methods and their timing** is to just 
- use `create-react-app` to make a project
- create a Component under `App` and a child under that as well
  - Maybe something like App > Parent > Child
    - Literally just call them that for clarity
- _In each component_ call these methods with a simple `console.log` and the method name
- Then change some props, change some state, etc. and see the order in which these methods fire!

This was absolutely the biggest help for me to get a better grasp on these React Lifecycle Methods. Oh, and did I mention to read the [React Docs on Components](https://reactjs.org/docs/react-component.html)?