Embracing the React Functional Component Lifecycle: A Simple Guide with Hooks

Embracing the React Functional Component Lifecycle: A Simple Guide with Hooks

Introduction:

If you're building things with React and using functional components, you might have heard about the "component lifecycle." In simpler terms, it's like understanding the different phases of a component's life – from birth to changes and finally saying goodbye. Let's walk through these phases using hooks, the functional component's way of handling things.

Watch Video : https://youtu.be/idF3jLdVtwk?si=nfHNzxlXDCntksjQ

1. Birth – Mounting Phase:

In the beginning, your component is born. We call this the "Mounting Phase." In class components, we had componentDidMount for this, but in functional components, we use the useEffect hook.

 React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // This runs after the component renders for the first time (componentDidMount)
    return () => {
      // This is like componentWillUnmount, it cleans up when the component is unmounted
    };
  }, []); // Empty dependency array means it runs once, similar to componentDidMount

2. Changes – Updating Phase:

Now, things change. Your component gets updated when there are changes in props or state. For this, we still use the useEffect hook, but this time, we watch for specific dependencies to decide when it should run.

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

function MyComponent({ data }) {
  const [value, setValue] = useState('');

  useEffect(() => {
    // This runs after every render if 'data' or 'value' changes (componentDidUpdate)
    // Your logic for handling updates goes here
  }, [data, value]);

3. Goodbye – Unmounting Phase:

Finally, it's time to say goodbye. When your component is about to be removed, we use useEffect with a cleanup function inside it. This is similar to componentWillUnmount in class components.

 React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // This runs after the component renders for the first time (componentDidMount)
    return () => {
      // This runs when the component is about to unmount (componentWillUnmount)
      // Clean up any subscriptions or tasks here
    };
  }, []);

Full Example Code:

import {useState} from "react";
import "./App.css";
import {useEffect} from "react";

function App() {
  const [isHover, setIsHover] = useState(false);
  const [sum, setSum] = useState(0);

  return (
    <>
      <div>
        <button
          onClick={() => {
            setIsHover(!isHover);
          }}
        >
          Hover Now
        </button>
        <button
          onClick={() => {
            setSum(sum + 1);
          }}
        >
          Update Sum
        </button>

        {isHover && <MountingComponent sum={sum} />}
      </div>
    </>
  );
}

export default App;

function MountingComponent({sum}) {
  useEffect(() => {
    console.log("Mounting Component");

    return () => {
      console.log("MountingComponent unmounted");
    };
  }, [sum]);

  return (
    <div
      style={{
        backgroundColor: "pink",
        width: "400px",
        height: "200px",
        borderRadius: "10px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        marginTop: "10px",
      }}
    >
      <p>{sum}</p>
    </div>
  );
}

//  React Component Update :  - Unmounting  then Mount

Conclusion:
Understanding the React functional component lifecycle with hooks is like navigating through the different chapters of a component's life story. The useEffect hook is your guide, helping you handle mounting, updating, and unmounting phases seamlessly in the functional component world. Embrace the simplicity of hooks, and your React journey will become even more enjoyable!