Component Lifecycle
Definition
Every React component goes through three main phases during its lifetime: Mounting (being inserted into the DOM), Updating (being re-rendered due to state/prop changes), and Unmounting (being removed from the DOM).
Explain Like I'm New
Think of a component like an actor in a play. Mounting is when they walk onto the stage and say their first line. Updating is when they interact with other actors and change their emotions. Unmounting is when their scene is over and they walk off the stage.
Real World Example
Mounting: You fetch the user's profile from an API the moment the page loads. Updating: The user types in an input box, and the screen updates to show the letters. Unmounting: The user logs out, and you cancel any pending API requests or timers so they don't crash the app in the background.
Common Use Cases
- •Fetching initial data (Mounting)
- •Responding to new props (Updating)
- •Cleaning up memory leaks like setInterval (Unmounting)
Architecture & Flow
Interactive Example
import React, { useState, useEffect } from 'react'; export default function LifecycleDemo() { const [count, setCount] = useState(0); // 1. MOUNTING & UNMOUNTING useEffect(() => { console.log("Phase 1: Component Mounted! (Like componentDidMount)"); return () => { console.log("Phase 3: Component Unmounted! (Like componentWillUnmount)"); }; }, []); // Empty array means run once // 2. UPDATING useEffect(() => { if (count > 0) { console.log(`Phase 2: Component Updated! Count is now ${count}`); } }, [count]); // Runs whenever 'count' changes return ( <div> <h2>Count: {count}</h2> <button onClick={() => setCount(c => c + 1)}>Trigger Update</button> </div> ); }
Interview Questions
basic
- What are the three phases of the component lifecycle?
- How do you simulate 'componentDidMount' using React Hooks?
intermediate
- How do you simulate 'componentWillUnmount' using Hooks?
- What triggers an 'Update' phase?
advanced
- What was the purpose of `shouldComponentUpdate` in class components, and what is its equivalent in functional components?
- In Strict Mode, why does React call the `useEffect` setup and cleanup functions twice on mount?
trick
- If a parent component unmounts, do its children unmount before or after the parent?