Sobes.tech
Junior — Middle

What are the lifecycle stages of a class component and how to implement them?

sobes.tech AI

Answer from AI

The lifecycle of a class component in React includes several main stages, each represented by corresponding methods:

  1. Mounting — when the component is created and inserted into the DOM.

    • constructor(props) — initializing state and binding methods.
    • static getDerivedStateFromProps(props, state) — synchronizing state with props (rarely used).
    • render() — rendering the markup.
    • componentDidMount() — called after the component is inserted into the DOM, suitable for API requests or subscribing to events.
  2. Updating — when the component receives new props or its state changes.

    • static getDerivedStateFromProps(props, state) — updating state based on new props.
    • shouldComponentUpdate(nextProps, nextState) — optimizing re-rendering, returning true/false.
    • render() — re-rendering.
    • getSnapshotBeforeUpdate(prevProps, prevState) — capturing information before DOM updates.
    • componentDidUpdate(prevProps, prevState, snapshot) — called after updates, suitable for DOM operations.
  3. Unmounting — when the component is removed from the DOM.

    • componentWillUnmount() — cleaning timers, canceling subscriptions.

Example implementation:

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

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

  shouldComponentUpdate(nextProps, nextState) {
    return nextState.count !== this.state.count;
  }

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

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

  render() {
    return <div>{this.state.count}</div>;
  }
}
What are the lifecycle stages of a class component… - sobes.tech