Blog>
Snippets

Class Components and Lifecycle Methods

Illustrate how React's lifecycle methods within a class component are involved in the reconciliation process.
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('Constructor: Component is being created with initial state.');
  }

  componentDidMount() {
    console.log('componentDidMount: Component has mounted.');
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate: Decide whether to proceed with the update.');
    return this.state.count !== nextState.count;
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate: Component has updated.');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount: Component is about to be unmounted.');
  }

  handleIncrement = () => {
    this.setState(prevState => ({ count: prevState.count + 1 }));
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleIncrement}>Increment</button>
      </div>
    );
  }
}
This class component demonstrates the usage of lifecycle methods in React. The constructor initializes the state. componentDidMount logs when the component mounts. shouldComponentUpdate returns a boolean to determine if re-rendering is necessary. componentDidUpdate logs when the component has updated. componentWillUnmount logs just before the component is removed from the DOM. There is also a render method that outputs the UI and a button to trigger a state change.