React Life Cycle Methods

Yashod Perera
5 min readDec 29, 2020

--

Photo by Steve Shreve on Unsplash

One of the Most Important lessons of react.

Hello Programmers, In this post you will be thought the theory and when to use react life cycles in class component and in a separate blog will do a practical example.

First Let’s get an understanding about life cycle methods and where to use and where not to use and following are the methods which we are talking about.

  • constructor()
  • render()
  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • getSnapshotBeforeUpdate()
  • componentDidMount()
  • componentDidUpdate()
  • componentDidUnmount()
  • componentDidCatch()

constructor()

This is the first method to call when component is mounted and there are two scenarios which are done inside a constructor which are,

  • Initialising the local state.
  • Bind event handlers to the instance.

Following is a sample constructor.

constructor(props) {
super(props);
this.state = { name: "Yashod" };
this.changeName() = this.changeName().bind(this);
}

Following are the common mistakes which people do.

  • Ignore super(props) in the constructor and then props cannot be accessed.
  • Use setState() in the constructor.
  • Directly copy the props to the state then prop updates are not reflected since constructor is not execute when component is updated.
constructor(props) {
super(props);
this.state = { name: this.props.name }; //Do not do this.
}

Note — If props need to be copy as a state when it updates use static getDerivedStateFromProps() .

render()

This is the only required field in the react class component and what it does is return rendering elements.

Following are the common mistakes which people do.

  • Use setState inside the render method.
  • Do side effects — Ex: API Calls.

Note — In this phase DOM is not updated.

static getDerivedStateFromProps()

This method is purely used if states are depends on the props and this life cycle method is return null as default or can be returned the state if needed to change it depend on the props update.

constructor(props){
super(props);
this.state = { name: "Yashod", age: 25 }
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.name != prevState.name) {
return {
name: nextProps.name,
age: nextProps.age
};
}
return null;
}

Note — The return should be the state and if this method returns null it will not affect the state.

shouldComponentUpdate()

There are some situations where we have to omit child components to re- render even parent component is rendered.

This is an important life cycle method which will return a boolean. If it returns true it will render the component or else not.

This method is use for performance optimisation.

shouldComponentUpdate(nextProps, nextState) {
if (next.props && next.props.name == this.props.name) {
return false; // Do not render again
}
return true; // Render
}

getSnapshotBeforeUpdate()

This is used to capture the DOM information before it updates and added it to the updated DOM. Ex — Capture the scroll location.

This function either return null or a value and that value can be captured in the componentDidUpdate() .

getSnapshotBeforeUpdate() {
if (something) {
return value;
}
return null;
}

componentDidMount()

This is the final stage of mounting process as well which is the commit phase where all the changes are updated to the DOM. In this stage following can be done.

  • Update the states.
  • Do side effects such as API Calls.
  • Any Subscriptions.
componentDidMount() {
// code
}

componentDidUpdate()

This is the final stage of the Updating life cycle. This method take 3 parameters as follows.

  • preProps — Previous props
  • preState — Previous State
  • snapshot — The value return from the getSnapshotBeforeUpdate()
componentDidUpdate(prevProps, preState, snapshot) { 
// code.
}

Following are the common mistakes which people do.

  • Using the setState without having a condition which will lead to infinite loop.
// Infinite Loop
componentDidUpdate(prevProps, preState, snapshot) {
setState({ name: "Amal" });
}
// Solution
componentDidUpdate(prevProps, preState, snapshot) {
if (prevProps.name != this.state.name) {
setState({ name: "Amal" });
}
}

componentDidUnmount()

This is the method which executes when component is unmounting. In this method what basically do is clean the component.

  • Unsubscribe services.
  • Cancelling network requests.

componentDidCatch()

This life cycle method is used handle errors. If we are not handle errors then the whole view will be disappeared.

constructor(props) {
super(props)
}
componentDidCatch(error, info) {
this.setState({error, info});
}
render(){
if (this.state.error) {
return <div> {this.state.error.message} </div>;
}
return <div> Some code </div>;
}

Following is the complete diagram which describes the order of the execution of lifecycle methods.

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

Four Stages of React Component

There are four main stages of a react component. Which are,

  • Mounting — When component is created.
  • Updating — When component is updated.
  • Un-mounting — When component is removed.
  • Error Boundaries — When error is occurred.

Important — Mainly there are only three stages which are mounting, updating and unmounting but error boundaries are considers sometime as a stage.

First let’s take Mounting stage.

Mounting

When component is mounting it is executing following methods in the given order.

Updating

In updating following five methods are executed.

Unmounting

In unmounting only the componentDidUnmount method will be executed.

References

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera
Yashod Perera

Written by Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor

No responses yet