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
- Mounting: The component is first rendered.
- Updating: The component re-renders due to state or prop changes.
- Unmounting: The component is removed from the DOM.
Here's a flowchart to visualize the lifecycle in functional components:
![]() |
- Render Phase:
- React renders the component.
- Commit Phase:
- React applies DOM updates.
useEffectruns after rendering.
- Cleanup (when applicable):
- Cleanup functions in
useEffectrun before the component unmounts or re-renders.
- Cleanup functions in
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
- Mounting:
useEffect(() => { ... }, [])
- Updating:
useEffect(() => { ... }, [dependencies])
- Unmounting:
- Cleanup function inside
useEffect.
- Cleanup function inside
No hints available.
Discuss with OthersAsk questions, share your thoughts, and discuss with other learners.
Loading discussion ...
