React Lifecycle Methods With Hooks Cheatsheet for Everybody

by Radoslaw Fabisiak

Intro to React lifecycle methods

Welcome to the react lifecycle tutorial, where I will explain all the things related to the react component lifecycle methods.

You’ll learn about the four main react component lifecycle stages, when they’re fired, and what is happening inside.

Next, we will talk about the methods used during these stages, which ones we need, and which ones we should avoid.

We won’t forget about these deprecated methods, so you will know which ones you should definitely refactor in your code and don’t use anymore.

Finally, in the last step, we will talk about react lifecycle hooks, and I’ll tell you how we can implement them to replace all of the lifecycle methods when we build reactjs functional components.

Let’s start!

And if you prefer video, here is the youtube version where I explain all of that:

React lifecycle diagram

In React, we have four main lifecycle phases.

Actually, I’d say there are three lifecycle phases and one phase for Error Handling, which I will tell you about a bit later.

Now, let’s focus on these three most popular and mostly used stages.

Anyway, even if not every developer cares about that stage, I still think it should be changed, and error handling should be implemented into every project because it can help us save a lot of time in the future.

So in the image, you can see the diagram containing the three life cycle stages: Mounting, Update and Unmounting.

The first two, I mean Mount and Update stage, are split into three phases: render, pre-commit, and commit.

The first phase of Mount and Update, called Render, happens when we do the pure rendering. Our DOM is not touched yet. We can stop or restart this phase until it is finished.

The second one, named Pre-Commit, is when we already have the first possibility of reading DOM by React app.

And the last one, named Commit, is when we have ready interaction with DOM, can manipulate Document Object Model, create side effect, and want to touch stuff outside our instance (component) like, for example, data fetching we can plan updates.

React Mount

Mount phase is the initial stage of the React component lifecycle and the moment when React creates our components and inserts them into the DOM.

Let’s see the component mount methods.

You will learn about when they’re fired, their responsibility, and when it is good to avoid using them.

React constructor

It’s a component lifecycle method that is fired before the react component is mounted.

Constructor is useful when we need to init components state, bind functions, or event handlers in our component.

We always need to remember to call super(props) to avoid situations when our component’s props are undefined.

React static getDerivedStateFromProps

This method is used in Mount and Update lifecycle.

This component lifecycle method is called just before the render method in both cases, mounting and updating.

It’s handy when we would like to change our component’s internal state by recognizing the props’ change implemented into the component.

Anyway, it’s not an easy method to use. You need to know how to do it. It will be much easier to use componentDidUpdate or memoization (ensuring our value in the render is recompiled when the inputs value change), but not in every case.

React render

This method is used in Mount and Update lifecycle, and it’s the only required method in the react component.

In react component lifecycle order, it’s called after getDerivedStateFromProps during the Mount cycle, or after shouldComponentUpdate and forceUpdate methods in Update cycle, new props or new components state will fire render method as well.

Render shouldn’t modify state and should just return elements like react elements, arrays, portals, string or numbers, and booleans or null, shortly it’s used mostly for creating or returning elements.

The returned value can be defined or can depend on component props or component state.

Interestingly, we can stop rendering component by returning false in function shouldComponentUpdate, and oppositely, we can force component to rerender by calling method forceUpdate.

React componentDidMount

This component lifecycle method is called after a component is mounted, like put into the DOM tree.

It’s used mostly for DOM operations, subscriptions, or data fetching, so it’s an excellent place to add all the data fetch actions, such as setState methods.

Anyway, you need to know that the component will rerender if you change state, but still before the browser will update the screen.

React componentWillMount

React componentWillMount is the deprecated method, which means you should refactor it to avoid future problems.

React update lifecycle methods

The update stage is the second phase of the React component lifecycle.

It means it can happen when the React application changes the props passed into the component’s component or internal state.

In the case of update, React calls methods in order as below:

static getDerivedStateFromProps shouldComponentUpdate  render  getSnapshotBeforeUpdate  componentDidUpdate

Now, let’s see what each of them does (getDerivedStateFromProps and render methods were described in the Mount section).

React shouldComponentUpdate

This method is always called when a state or props changed.

Fires before render methods, and what is more interesting, this method doesn’t fire when we use method forceUpdate.

React shouldComponent update method works like, if it returns true (that is the default value), React component will rerender, but if it returns false, component will not render again.

Used mostly for improving performance, to check if rerender is definitely necessary, and stop it when it’s not.

One more thing that you should know about that method is that you can use PureComponents instead of messing with this function because React PureComponent has built-in comparison and will not rerender when not necessary.

React getSnapshotBeforeUpdate

React getSnaphostBeforeUpdate is fired after, or I’d say during render method, just before render will update DOM.

It’s not very popular to use, and it’s used only in exceptional cases, for example, news feeds with infinite scrolls.

React componentDidUpdate

This method is very similar to the componentDidMount, and it’s fired after the finished render method, but in the Update stage of React component lifecycle.

Anyway, it’s not called after the initial render, which is called in the Mount stage of the React component lifecycle.

As well as the componentDidMount, it’s used mostly for DOM operations or data fetching.

React componentWillUpdate (deprecated)

React componentWillUpdate is the deprecated method, which means you should refactor it to avoid future problems.

React componentWillReceiveProps (deprecated)

React componentWillReceiveProps is the deprecated method, which means you should refactor it to avoid future problems.

React Unmount

It’s the last stage of the React component lifecycle.

Unmounting is when a component is being removed from the Document Object Model (DOM), and it has only one method called during this stage, the componentWillUnmount.

React componentWillUnmount

It’s the only method called during the unmount stage, and it’s called precisely before a component is unmounted and destroyed.

Like the componentDidMount, it’s used mostly for DOM operations or data fetching, but in this case, we use that method to clean all of the changes, listeners, or subscriptions that we created in componentDidMount or componentDidUpdate methods.

React Component Error Handling

Error handling is the lifecycle stage that I wouldn’t name lifecycle, more like exception handler, but still is one of the most crucial parts in the component lifecycle.

This part is responsible for properly handling errors during rendering, calling constructor, or another part of the lifecycle method.

Proper error handling is very important for every React (and every other) application and always should be done carefully because it will save us tons of time and maybe even more good mood in the future.

We have two methods possible to fire in this phase, static getDerivdedStateFromError, and componentDidCatch.

React static getDerivedStateFromError

React static getDerivedStateFromError is the method that is fired when our component throws an error.

We should use it to take the error as a param and change the state to the component.

Next, we can see in the UI about something went wrong.

React componentDidCatch

This method works a bit differently than componentDidCatch because it takes the two params, one is an error, and the second one is info, which shows which part of the application created an error.

It’s useful when we have detailed logs and will use this method to pass information to the logs that we can monitor as the developer or admin.

React lifecycle hooks

All of the react component lifecycle stages help us handle most of the moments precisely and perform actions that we need at that moment, but not always we need them.

In many applications, we will need to catch only moments when we init component, update, and unmount, without going for all of the small parts.

In this case, we can replace most of that with a useEffect hook. 

useEffect hook explanation

React useEffect hook can be used as a successful replacement for componentDidMount, componentDidUpade, and componentWillMount.

It’s named useEffect from the name of all of the actions that we performed out of the instance (side-effects).

We can fire useEffect like componentDidMount and componentDidUpdate:

useEffect(()=>{
  //some logic here
});

In this case, the useEffect hook will start on both actions and fire when the component inits or changes state. 

We can fire useEffect like componentDidMount only:

useEffect(()=>{
  //some logic here
},[]);

In this case, the useEffect hook will start only the first time, like in the Mount phase.

We can fire useEffect like componentDidUpdate related to the one part of the instance only:

useEffect(()=>{
  //some logic here
},[name]);

In this case, the useEffect hook will start only when the state “name” will be changed.

We can fire useEffect like componentWillUnmount:

useEffect(()=>{
  listen();
  return function cleanup() {
    stopListening();
  }
});

In this case, the useEffect hook will start on the init, start function listen, and when a component will go into unmounting, useEffect will start function cleanup.

Summary of react lifecycle methods

Congratulations, now you know all about the react component lifecycle!

You’ve learned about how to use hooks to simplify your work with lifecycle as well.

It is a long lesson and full of knowledge, but I’m sure now your code will look better, and you will have real deep-inside knowledge about how react components work during their lifecycle.

It’s definitely not something that every beginner should know, but experienced developers must have this knowledge to avoid future mistakes.

Let us know in the comments what topic is the most interesting for you and what you would like to learn now!

Thanks for reading,
Radek from Duomly

Radoslaw Fabisiak

If you liked it share and comment!