18) Component Lifecycle
Functional Component Lifecycle Phases
In modern React, functional components don’t have lifecycle methods like class components. Instead, lifecycle behavior is handled using hooks, mainlyuseEffect.
Even in functional components, the lifecycle still conceptually has 3 phases,
i) Mounting (Component created)
ii) Updating (State/props change)
iii) Unmounting (Component removed)In React functional component the useEffect hook is use as a Lifecycle Controller.
TheuseEffecthook replaces,
i)componentDidMount
ii)componentDidUpdate
iii)componentWillUnmount
Depending on how you use it, it behaves differently.Lifecycle Mapping with Examples
i) Mounting Phase (componentDidMount)
Runs only once when component mounts
It is equivalent to componentDidMount()import { useEffect } from "react"; const App = () => { useEffect(() => { console.log("Component Mounted"); }, []); // empty dependency array, runs only once return <h1>Hello World</h1>; }ii) Updating Phase (componentDidUpdate)
Runs when dependency changes
It is equivalent to componentDidUpdate(prevProps, prevState)import { useState, useEffect } from "react"; const Counter = () => { const [count, setCount] = useState(0); useEffect(() => { console.log("Count Updated:", count); }, [count]); // runs only when count changes return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }iii) Unmounting Phase (componentWillUnmount)
It uses Cleanup function
It is equivalent to componentWillUnmount()import { useEffect } from "react"; const Timer = () => { useEffect(() => { const interval = setInterval(() => { console.log("Running..."); }, 1000); return () => { clearInterval(interval); console.log("Component Unmounted"); }; }, []); return <h1>Timer Running</h1>; }