Sagar Medtiya
Sagar Medtiya

Sagar Medtiya

Component Lifecycle­čîÇ in ReactJS­čÜÇ

Component Lifecycle­čîÇ in ReactJS­čÜÇ

Sagar Medtiya's photo
Sagar Medtiya
┬ĚAug 26, 2022┬Ě

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

In ReactÔÜŤ´ŞĆ, component are designed to follow the natural cycle­čÜ▓ of life. As everyone goes through a cycle of born, grow and die. Each component in react goes through Mounting, Updating and Unmounting. Below is a good illustration of how react lifecycle works.

image.png Image Source: wojtekmaj

React provides access to certain built-in events/methods called lifecycle­čîÇ hooks or lifecycle methods. These methods give you opportunities to control and manipulate how a component reacts to changes in the application.

LetÔÇÖs have a look at each phase in a component lifecycle:

­čŹÇInitialization

This is the first stage in react lifecycle, in this stage­č¬ť the component is constructed with provided props and default states. This is where we define defaults and initial values for this.props and this.state.

­čŹÇMounting

This is the next state­č¬ť in React Lifecycle. After you have prepared the basic code requirement, states and props, you need to mount on the browser. This is done via browser DOM. ReactÔÜŤ´ŞĆ uses virtual DOM to put all the elements into the memory. Note: Child component is mounted before the parent component.

­čî┐constructor

constructor()­čĹĚ method is called when the component is initiated and itÔÇÖs the best place to initialize our state. The constructor method takes props as an argument and starts by calling super(props) before anything else.

class Todo extends React.Component {
  //Setting the initial state of the Component
  constructor() {
    super();
    this.state = {
      task: "",
      isCompleted: false,
      dateCreated: ""
    }
  }
}

­čî┐componentDidMount

This is the final ReactJS hook­č¬Ł method that is executed after the component mounts the DOM. This method is executed after first render and is executed only on client side. This is a great place to set up initial data. Child component's componentDidMount runs before parent's componentDidMount. It runs­čĆâÔÇŹÔÖé´ŞĆ only once. You can also make the right API calls under this method so that you can retrieve the data the right way.

­čî┐static getDerivedStateFromProps

This method is called (or invoked) before the component is rendered to the DOM on initial mount. It allows a component to update its internal state in response to a change in props. To update the state -> return object with new values.

For example,

static getDerivedStateFromProps(props, state){
    return{
          points: 200 // update state with this
   }
}

­čŹÇUpdating

The third stage­č¬ť starts when the component has been adopted on the browser. During this phase the component is already inserted into DOM. A component is updated when there is a change in state and props React basically has three built-in methods that are called while updating the components.

­čî┐shouldComponentUpdate

The method tells the program­čÉ▒ÔÇŹ­čĺ╗ about the state of rendering when it is updated. If new props or rules are being updated, then a rendering can be done or skipped. This is important to code in properly as there are evolving states in the program as well. Updating the method as true/false is the proper approach. The default here is true, which can be changed as per the code.

­čî┐getSnapshotBeforeUpdate

This hook­č¬Ł is executed right after the render method is called. It has access to props and state before the update. It is handy when you want some DOM info or want to change DOM just after an update is made. For example, getting information about the scroll position.

getSnapshotBeforeUpdate(prevProps, prevState){
    //capture the scroll position so we can adjust scroll later
    if(prevProps.list.length < this.props.list.length){
        const list = this.listRef.current;
        return list.scrollHeight - list.scrollTop;
    }
    return null;
}

Value queried from the DOM in getSnapshotBeforeUpdate will refer to the value just before the DOM is updated. It doesn't work on its own and used in conjunction with the componentDidUpdate lifecycle­čîÇ method.

­čî┐componentDidUpdate

This method is called just after the re-rendering of the component. This hook­č¬Ł has prevProps and prevState available. This lifecycle method is invoked after the getSnapshotBeforeUpdate is invoked.

componentDidupdate(prevProps, prevState, snapshot){
    if(condition){
        this.setState({..})
    }
    else{
        //do something else o loop
    }
}

­čŹÇUnmounting

The final stage­č¬ť of unmounting is essential as it doesnÔÇÖt require the component and gets unmounted from the DOM. As the final state­č¬ť, it is designed to produce the outcome via unmounting.

­čî┐componentWillUnmount

If there are any cleanup actions like canceling API calls or clearing any caches in storage you can perform that in the componentWillUnmount method. You cannot use setState inside this method as the component will never be re-rendered.

These are the methods that you are most likely come across. I've omitted some deprecated methods or are set to be deprecated in the very near future.

Thanks for reading­čĺŚ

Reference:

Did you find this article valuable?

Support Sagar Medtiya by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this