Going further with React lifecycle methods

In my previous article Getting started with React, I covered getting started with writing a stateful and stateless components, props and container components. These are the foundations of any React application but when you start to add more complexity to your components, you’ll want to hook onto React’s lifecycle methods.

A components life changes over time with state. Before or after state changes, you may wish to invoke additional behaviour. In this article, I’m going to cover the React lifecycle methods with examples you may want to take advantage of in your components.

The lifecycle names are pretty self-explanatory. But for my own learning, understanding and future reference, I’d like to provide an example or notes of each. The React docs pretty much cover this if you wish to read what I’m about to say, by someone more intelligent.

Mounting

componentWillMount()

This method is called before a component is rendered. One of the fewer used lifecycle methods. This method runs on the server and is unaware of the DOM.

componentDidMount()

This method is called after a component is rendered and is aware of the DOM. This is also a great place to talk to any non-React plugins.

If you are not using the Flux pattern in your application, you may use this lifecycle method to perform any AJAX calls your render method needs.

Because componentDidMount() is aware of the DOM, we can do the following;

componentDidMount() {
const title = ReactDOM.findDOMNode(this.refs.title).innerHTML
console.log(title)
}

render() {
return <h1 ref=”title”>Hello World</h1>
}

Updating

componentWillReceiveProps(nextProps = {})

Only when a components props have changed is this method invoked with a new props object.

shouldComponentUpdate(nextProps = {}, nextState = {})

This lifecycle method should return true or false and not itself trigger an update. You can perform your own additional checks to see if you need to re-render.

Returning false will skip the render() lifecycle method.

componentWillUpdate(nextProps = {}, nextState = {})

Similar to componentWillMount(), this method is called when an already mounted component is about to update. The .setState() method is not permitted within componentWillUpdate().

componentDidUpdate(prevProps = {}, prevState = {})

Again, similar to componentDidMount(), this method is called after the render() method. Here is where you will want to invoke any 3rd party JS libraries as you have access to the DOM within this lifecycle method.

Unmounting

componentWillUnmount()

This method is called before it is removed from the DOM. You should use this method for any further garbage collection including the removal of event listeners.

Like what you read? Give Jamie Barton a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.