Sobes.tech
Junior — Middle

What stages do React components go through from creation to removal from the DOM?

sobes.tech AI

Answer from AI

React components go through several key lifecycle phases from creation to removal from the DOM:

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

    • Constructor
    • static getDerivedStateFromProps
    • render
    • componentDidMount
  2. Updating — occurs when props or state change.

    • static getDerivedStateFromProps
    • shouldComponentUpdate
    • render
    • getSnapshotBeforeUpdate
    • componentDidUpdate
  3. Unmounting — removing the component from the DOM.

    • componentWillUnmount
  4. Error Handling — when errors occur in child components.

    • static getDerivedStateFromError
    • componentDidCatch

Example of using lifecycle methods in a class component:

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

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

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

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

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

In functional components with hooks, similar phases are implemented via useEffect and other hooks.