PresentationInteractive, narrated presentation of the section content.

ContentDetailed description of the section content.

React Functional Component Lifecycle with <strong>useEffect</strong>

React lifecycle events for functional components are managed using useEffect, which can mimic the behavior of lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount from class based React components.


Visual Overview

Phases of the Lifecycle

  1. Mounting: The component is first rendered.
  2. Updating: The component re-renders due to state or prop changes.
  3. Unmounting: The component is removed from the DOM.

Here's a flowchart to visualize the lifecycle in functional components:

  1. Render Phase:
    • React renders the component.
  2. Commit Phase:
    • React applies DOM updates.
    • useEffect runs after rendering.
  3. Cleanup (when applicable):
    • Cleanup functions in useEffect run before the component unmounts or re-renders.

Example Code

Let’s demonstrate these lifecycle phases using useEffect:

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

const LifecycleDemo = () => {
  const [count, setCount] = useState(0);

  // Runs only once when the component is mounted
  useEffect(() => {
    console.log("Component mounted");

    // Cleanup: Runs when the component unmounts
    return () => {
      console.log("Component unmounted");
    };
  }, []); // Dependency array is empty, so it runs only on mount and unmount.

  // Runs every time 'count' changes
  useEffect(() => {
    console.log(`Count updated to ${count}`);

    // Cleanup: Runs before the next effect or on unmount
    return () => {
      console.log(`Cleanup before count changes or unmount: ${count}`);
    };
  }, [count]); // Dependency array has 'count', so it runs when 'count' changes.

  return (
    <div>
      <h1>React Lifecycle with useEffect</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default LifecycleDemo;

Graph for Lifecycle Events

  1. Mounting:
    • useEffect(() => { ... }, [])
  2. Updating:
    • useEffect(() => { ... }, [dependencies])
  3. Unmounting:
    • Cleanup function inside useEffect.

No hints available.

Discuss with OthersAsk questions, share your thoughts, and discuss with other learners.

Loading discussion ...