Sobes.tech
Junior — Middle

Explain the sequence of stages of a React component's existence and operation, from creation to removal from the DOM.

sobes.tech AI

Answer from AI

In React, a component's lifecycle goes through several key stages:

  1. Mounting — creating and inserting the component into the DOM.

    • Constructor (constructor) — initializes state and binds methods.
    • static getDerivedStateFromProps — updates state based on props.
    • render — returns JSX for display.
    • componentDidMount — called after the component is inserted into the DOM; here you can initiate requests or subscriptions.
  2. Updating — occurs when props or state change.

    • static getDerivedStateFromProps — updates state.
    • shouldComponentUpdate — decides whether to re-render the component.
    • render — updates JSX.
    • getSnapshotBeforeUpdate — captures information before the DOM is updated.
    • componentDidUpdate — called after the component updates.
  3. Unmounting — removing the component from the DOM.

    • componentWillUnmount — cleanup timers, cancel subscriptions.

Example with class:

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

  componentDidMount() {
    console.log('Component inserted into DOM');
  }

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

  componentWillUnmount() {
    console.log('Component will be removed from DOM');
  }

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

In functional components with hooks, similar stages are implemented through useEffect with different dependencies.