React Lifecycle Methods - The Basics

stlnick

Nick

Posted on August 17, 2020

React Lifecycle Methods - The Basics

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 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 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.

componentDidUpdate(prevProps) {
  if (this.props.userID !== prevProps.userID) {
    const dataObject = this.fetchData(this.props.userID);
    this.setState(dataObject)
  }
}
Enter fullscreen mode Exit fullscreen mode

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


Definitely still go to the React Docs on Components 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?

💖 💪 🙅 🚩
stlnick
Nick

Posted on August 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related