What is React Component Life Cycle? 🔄

The React Component Lifecycle is a series of methods that are invoked at different stages of a component’s existence. These stages help you control how your component behaves and interacts with other parts of your application. Understanding these stages allows developers to effectively manage their components and optimize performance.

Mounting Stage ⬆️

Mounting is the phase where a component is being created and inserted into the DOM. The main methods in this stage include:

Updating Stage 🔄

Updating occurs when the component’s state or props change. A component can be updated in various ways, such as when its state changes, when the parent component re-renders, or when new props are received. The main methods in this stage include:

Unmounting Stage ⬇️

Unmounting is the phase where the component is being removed from the DOM. The main method in this stage is:

How did useEffect() change the React Lifecycle Methods? 🔄🛠️

useEffect is one of the most important hooks in React, introduced to manage side effects in functional components. It allows you to perform side effects in your components, such as fetching data, interacting with the DOM, or subscribing to external data sources.

What is useEffect? ⚙️

useEffect is a hook that accepts a function and an optional array of dependencies. The function you pass to useEffect() is your effect, and it will run after the render is committed to the screen. If you provide the optional array of dependencies, useEffect() will only re-run the effect when one of the dependencies has changed.

Here's an example to illustrate:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // useEffect here acts like componentDidMount
    console.log('Component did mount');
    fetch('<https://api.example.com/data>')
      .then(response => response.json())
      .then(data => setData(data));

    return () => {
      // Here acts like componentWillUnmount
      console.log('Component will unmount');
    };
  }, []); // Empty dependency array ensures this runs once

  useEffect(() => {
    // Here it acts like componentDidUpdate
    console.log('Component did update');
  }, [data]); // Runs whenever the state changes for data

  return <div>{data ? data : 'Loading...'}</div>;
}

export default MyComponent;

Detailed Explanation 🔍