React Component Life Cycle Methods with Examples

React Component Life Cycle Methods with Examples

Introduction:

React components allow you to see how the components are created, updated, and deleted from the DOM. Only Class components use the React lifecycle methods. Everything in React works with a Component.

React lifecycle provides a better performance, side effects handling, and resources management. Lifecycle methods manage the component’s behaviour and perform the specific operations at different phases.

In this article, we will discuss React component lifecycle methods with examples understand how they work in class components.

React Lifecycle Methods:

The React lifecycle is divided into three main phases that are explained below in detail:

1. Mounting

In this phase, components are created and a component to the DOM. It contains four methods, such as constructor(), getDerivedStateFromProps(), render(), and componentDidMount(), etc.

constructor(): This method is used for initializing the state and binding the components. It’s called when the component is initialized, but before its rendering.

Example

Code:

import React from "react";
class Component extends React.Component {
  constructor(props) {
    super(props);
    this.state = { show: true };
    console.log("Constructor called");
  }

  componentWillUnmount() {
    console.log("Component will unmount!");
  }

  render() {
    return (
      <div>
        <p>Component is called in lifecycle Methods</p>
      </div>
    );
  }
}
export default Component;        

Output:

Component is called in lifecycle Methods        

getDerivedStateFromProps(): This method helps to update the state before rendering the element in the DOM. It takes two parameters, such as state and props.

Example

Code:

import React from "react";

class Title extends React.Component {
  constructor(props) {
    super(props);
    this.state = { pageTitle: "Welcome" };
  }

  static getDerivedStateFromProps(props, state) {
    if (props.newTitle !== state.pageTitle) {
      return { pageTitle: props.newTitle };
    }
    return null;
  }

  render() {
    return <h1>{this.state.pageTitle}</h1>;
  }
}

export default function App() {
  return (
    <div>
      <Title newTitle="Hello React!" />
    </div>
  );
}        

Output:

Hello React!        

render(): Its methods are only used in class components. This method helps to return the JSX element, and you can easily update the DOM.

Example

Code:

import React from "react";
class Header extends React.Component {
  render() {
    return (
      <div>
        <h1>Welcome to React Lifecycle</h1>
        <p>This text is rendered using the render() method.</p>
      </div>
    );
  }
}
export default Header;        

Output:

Welcome to React Lifecycle
This text is rendered using the render() method.        

componentDidMount(): This method is used after the component has been rendered to the DOM element.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: "Loading..." };
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({ message: "Welcome to React Lifecycle!" });
    }, 3000);
  }

  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    );
  }
}

export default Welcome;
ReactDOM.render(<Welcome />, document.getElementById("root"));        

Output:

2. Updating:

These methods help to update the component using a state or props. It contains five methods such as getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), and componentDidUpdate(), etc.

getDerivedStateFromProps(): This is used when the component has been updated. It updates the props and state as a parameter. It contains two parameters for updating, like nextProps and nextState.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class ColorBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: "red" }; // default state
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.newColor !== prevState.color) {
      return { color: nextProps.newColor }; // update state if prop changes
    }
    return null;
  }

  render() {
    return (
      <div>
        <h1 style={{ color: this.state.color }}>
          The color is red.
        </h1>
      </div>
    );
  }
}
export default ColorBox;
ReactDOM.render(<ColorBox newColor="blue" />, document.getElementById("root"));        

Output:

The color is red.        

shouldComponentUpdate(): This method helps to return a Boolean value that specifies whether React is performing rendering or not. By default, its value is true.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  shouldComponentUpdate(nextProps, nextState) {
        if (nextState.count > 10) {
      console.log("Update blocked! Count exceeded 10.");
      return false;
    }
    return true;
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    console.log("Rendering... Count =", this.state.count);
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}
export default Counter;

ReactDOM.render(<Counter />, document.getElementById("root"));        

Output:

Article content

render(): This method is called when your components are updated and re-render the HTML to the DOM with some changes.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = { favoritecity: "Delhi" };
  }

  changeCity = () => {
    this.setState({ favoritecity: "Mumbai" });
  };

  render() {
    return (
      <div>
        <h1>My Favorite City is {this.state.favoritecity}</h1>
        <button type="button" onClick={this.changeCity}>
          Change City
        </button>
      </div>
    );
  }
}
export default Header;
ReactDOM.render(<Header />, document.getElementById("root"));        

Output:


Article content

getSnapshotBeforeUpdate(): If this method is used in your code, the componentDidUpdate() method should also be present. It helps to manage some information before changes are applied.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class Message extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: "Hello" };
  }

  changeMessage = () => {
    this.setState({ text: "Welcome to React!" });
  };

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("Previous message was:", prevState.text);
    return prevState.text;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("Snapshot from getSnapshotBeforeUpdate:", snapshot);
    console.log("Current message is:", this.state.text);
  }

  render() {
    return (
      <div>
        <h1>{this.state.text}</h1>
        <button onClick={this.changeMessage}>Change Message</button>
      </div>
    );
  }
}
export default Message;
ReactDOM.render(<Message />, document.getElementById("root"));        

Output:


Article content

componentDidUpdate(): This method is called when the component has rendered and updated in the DOM. They are used for performing side effects, API calls based on the state and props. These are not just for updating the state, but it's only used for an infinite loop of re-rendering.

Example

Code:

import React from "react";

class ClickTracker extends React.Component {
  constructor(props) {
    super(props);
    this.state = { clicks: 0 };
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.clicks !== this.state.clicks) {
      document.title = `You clicked ${this.state.clicks} times`;
      console.log(`Updated document title to "${document.title}"`);
    }
  }

  handleClick = () => {
    this.setState({ clicks: this.state.clicks + 1 });
  };

  render() {
    return (
      <div>
        <h1>Clicks: {this.state.clicks}</h1>
        <button onClick={this.handleClick}>Click Me</button>
      </div>
    );
  }
}
export default ClickTracker;        

Output:


Article content

3. Unmounting:

The last phase in the React lifecycle method is called when the component has been removed from the elements. This is used for performing the close operations to ensure that your component is removed from the DOM tree. It contains only one method, like componentWillUnmount(), etc.

componentWillUnmount(): This method is used when your component has been deleted or removed from the DOM. It can be easily removed the component from the DOM, but this cannot update the state or render it.

Example

Code:

import React from "react";
import ReactDOM from "react-dom";

class TimerComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  componentDidMount() {
    // Start a timer when the component mounts
    this.timer = setInterval(() => {
      this.setState({ seconds: this.state.seconds + 1 });
    }, 1000);

    // Add a window resize listener
    window.addEventListener("resize", this.handleResize);
    console.log("Timer started and resize listener attached.");
  }

  componentWillUnmount() {
    // Cleanup timer
    clearInterval(this.timer);

    // Remove event listener
    window.removeEventListener("resize", this.handleResize);

    console.log("Timer stopped and resize listener removed.");
  }

  handleResize = () => {
    console.log("Window resized:", window.innerWidth, "x", window.innerHeight);
  };

  render() {
    return (
      <div>
        <h1>Timer: {this.state.seconds} seconds</h1>
        <p>Resize the window to see event logs in the console.</p>
      </div>
    );
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state = { show: true };
  }

  toggle = () => {
    this.setState({ show: !this.state.show });
  };

  render() {
    return (
      <div>
        <button onClick={this.toggle}>
          {this.state.show ? "Stop Timer" : "Start Timer"}
        </button>
        {this.state.show && <TimerComponent />}
      </div>
    );
  }
}

export default TimerComponent;
ReactDOM.render(<App />, document.getElementById("root"));        

Output:


Article content

Conclusion

This article provides a deeper understanding of React Components with lifecycle methods from basic to advance. React lifecycle methods are used in only class components, not in functional components. These lifecycle methods are used for handling the state, managing side effects, optimizing re-rendering, and managing errors easily.

Lifecycle phase provides many methods like componentDidMount(), componentDidUpdate(), and componentWillUnmount(), etc, to manage logic effectively.

I recommend that you learn ReactJS from the Tpoint tech website, as it provides React.js tutorials, interview questions, and all its related topics is simple language.

To view or add a comment, sign in

More articles by Udhav Khera

Others also viewed

Explore content categories