What is React Component Lifecycle?

React component lifecycle refers to the various stages or phases that a React component goes through during its existence. Understanding the component lifecycle is crucial for managing the behavior of your components and performing tasks at specific points in a component’s life. In React, there are three main phases of a component’s lifecycle:

  1. Mounting: This phase involves the initial creation of a component and its insertion into the DOM.
  • constructor(): This is the first method that gets called when a component is created. You can use it to set up initial state and bind event handlers.
  • render(): This method is responsible for rendering the component’s JSX and is called whenever the component’s state or props change.
  • componentDidMount(): This method is called after the component has been rendered to the DOM. It’s a good place to perform tasks like making API calls or setting up subscriptions.
  1. Updating: This phase occurs when a component is re-rendered due to changes in its state or props.
  • render(): As mentioned earlier, the render method is called whenever the component needs to be re-rendered.
  • componentDidUpdate(): This method is called after the component has re-rendered due to changes in state or props. It’s useful for performing actions after an update, like updating the DOM or making additional API requests.
  1. Unmounting: This phase happens when a component is removed from the DOM.
  • componentWillUnmount(): This method is called just before the component is removed from the DOM. It’s a good place to perform cleanup tasks like unsubscribing from subscriptions or releasing resources.

In addition to these phases, React 16.3 and later introduced new lifecycle methods and made some existing methods obsolete due to changes in React’s design patterns. The following methods are considered legacy and may be unsafe to use:

  • componentWillMount()
  • componentWillReceiveProps()
  • componentWillUpdate()

Instead, React introduced safer alternatives, such as getDerivedStateFromProps() and getSnapshotBeforeUpdate().

It’s important to note that with the introduction of React hooks, you can often achieve the same functionality as the class-based lifecycle methods using functional components. Hooks like useEffect replace many of the lifecycle methods for managing side effects and component behavior.

Understanding the component lifecycle is essential for building React applications, as it allows you to control when and how certain actions or operations are performed within your components, ensuring that your application behaves as expected and is efficient in its resource usage.

React Component has LifeCycle through which we can monitor or manipulate React Component during its phases

React three main phases are

  • Mounting
  • Updating
  • Unmounting

What is Mounting in React Component phase?

Mounting in React Component phase is the phase in which we put Elements in DOM

React Mounting Methods?

React has four inbuilt Mounting methods

  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount()

in the following four mounting method render() method is required while the other we use on behalf of the need

constructor()

the constructor method is called when React Component initialize

Example:

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "blue"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));

What is getDerivedStateFromProps in React?

in the mounting phase getDerivedStateFromProps is called before the render() method

getDerivedStateFromProps change the State properties by Props

getDerivedStateFromProps has two parameters one is state and another is props

Example

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Color favcol="blue"/>, document.getElementById('root'));

render

render() is that method through that HTML output takes place in DOM

Example

class Color extends React.Component {
  render() {
    return (
      <h1>my color is </h1>
    );
  }
}

ReactDOM.render(<Color/>, document.getElementById('root'));

What is componentDidMount in React?

React Component lifecycle in which componentDidMount method is called after render method call means after HTML output in DOM

Example

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "blue"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Color/>, document.getElementById('root'));

React Updating lifecycle after mounting

React has five inbuilt methods that is called while updating DOM

  • getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

getDerivedStateFromProps()

getDerivedStateFromProps() the method is called just after the update

Example:

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Color favcol="yellow"/>, document.getElementById('root'));

No update will take place due to the getDerivedStateFromProps() method

shouldComponentUpdate method

the default value of shouldComponentUpdate is true. if shouldComponentUpdate will return false then no change will take place

Example of shouldComponentUpdate with return false

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));


No change will take place with return false

Example of shouldComponentUpdate with return true

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));

Update will take place and value will be blue after click

render method in Update

After the update render() will be called to rerender the HTML to the DOM

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));

getSnapshotBeforeUpdate in the Update phase

getSnapshotBeforeUpdate is associate with componentDidUpdate() without componentDidUpdate() association getSnapshotBeforeUpdate will show error

getSnapshotBeforeUpdate has access to the State and Props of React before the update

componentDidUpdate() has access to State and Props after the Update

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));

componentDidUpdate method

componentDidUpdate method is called after the update to DOM

Example

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));


Unmounting lifecycle

Unmounting is the reverse of mounting it means in Unmounting HTML will get removed from DOM

Unmounting has only one inbuilt method

  • componentWillUnmount()

Example

class Color extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Colorchild  />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Colorchild extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

ReactDOM.render(<Color />, document.getElementById('root'));

Leave a Comment