Sobes.tech
Middle

Tell about the lifecycle of a React component: main stages mount, render, unmount.

sobes.tech AI

Answer from AI

The React component lifecycle includes several key stages:

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

    • In class components, the constructor is called, then render(), followed by componentDidMount().
    • In functional components with hooks — the component function is called first, then the useEffect hook with an empty dependency array.
  2. Rendering — the process of generating the virtual DOM based on the current state and props.

    • The render() method is called in class components.
    • In functional components — the component function is invoked.
    • Rendering can occur when state (setState) or props change.
  3. Updating — occurs when state or props change.

    • In class components, shouldComponentUpdate() and componentDidUpdate() methods are called.
    • In functional components — the component function and hooks are called again.
  4. Unmounting — removing the component from the DOM.

    • In class components, componentWillUnmount() is called to clean up resources.
    • In functional components — cleanup function in useEffect.

Example with a functional component and hooks:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // componentDidMount
    console.log('Mounted');

    return () => {
      // componentWillUnmount
      console.log('Unmounted');
    };
  }, []);

  return <div>Hello, React!</div>;
}

Thus, the lifecycle manages the creation, updating, and removal of the component, enabling side effects and optimizing application performance.

Tell about the lifecycle of a React component: main… - sobes.tech