React Lifecycle Events

Posted by Nolan Hughes on October 8th, 2018

React’s lifecycle methods can be problematic at times, but are an extremely important aspect of React developing. When used in the wrong way they can cause side effects that can be detrimental but are necessary for things like AJAX calls.

There are three main categories for React’s lifecycle methods: mounting, updating, and unmounting. Here is a chart from Dan Abramov that does a good job of illustrating the lifecycles.

Mounting

Setup props and state

This is where the initial states and default props get set up. You can use the constructor to set the initial state and then outside of the component you can set any default props on it that you want.

getDerivedStateFromProps

This is called after the component is created as well as when it receives a new prop. Basically if you need to update state based on a prop change, use this.

Render

This mounts the component onto the browser. It’s a pure method so it is a good idea to not use anything that won’t have the same output every time in it. AJAX calls would be something to avoid and try to think of this like you would a functional component.

componentDidMount

This is a fun one. This hook is executed right after the component did mount, right after the first render. API or AJAX calls should happen during this lifecycle method.

Updating

getDerivedStateFromProps

I already went over this lifecycle method above just wanted to make sure it was clear that it also gets called again when updating.

shouldComponentUpdate

This just determines whether or not react should update the DOM. It only returns a Boolean value.

Render

Same as above.

getSnapshotBeforeUpdate

This lifecycle is invoked right before the most recently rendered output is committed to the DOM. This allows you to capture current values so you can save them. Whatever value is returned from this will be passed to componentDidUpdate.

componentDidUpdate

This is triggered when the updated component has been updated. Use this one to re trigger third party libraries or things of that nature.

Unmounting

componentWillUnmount

This is basically your clean up crew. It is executed right before the component gets removed from the DOM. Basically anything that the component was holding on to should get removed so that isn’t still hanging around when the component doesn’t exist anymore.