Join the discussion
Comments
Loading comments...
Cookie preferences
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Join the discussion
Loading comments...
We use essential cookies for sign-in and preferences. With your permission, we also use basic analytics to improve lessons.
Mount, update aur unmount phases β dekho kaunse hooks aur effects har stage mein chalte hain.
Har React component teen lifecycle phases se guzarta hai: Mount (DOM mein pehla render), Update (state ya prop changes ki wajah se re-renders), aur Unmount (DOM se removal). Hooks ke saath, yeh phases class lifecycle methods ki jagah useEffect, useLayoutEffect, aur cleanup functions se express hoti hain.
React aapka function component call karta hai, JSX evaluate karta hai, aur resulting DOM nodes insert karta hai. useState initializers run hote hain, useRef objects create hote hain. DOM insertion ke baad, useLayoutEffect synchronously run karta hai, phir useEffect paint ke baad asynchronously run karta hai.
Jab setState ya nayi prop aati hai, React ek re-render queue karta hai. Re-render ke dauran, hooks mount ki tarah same order mein call hote hain. React naye vs purane output compare karta hai aur DOM patch karta hai. Effects re-run karne se pehle, React previous render ke effects ki cleanup functions run karta hai.
Har effect re-run se pehle (aur unmount par), React previous effect ki cleanup function call karta hai. Yeh timers clear karne, fetches cancel karne, aur events se unsubscribe karne ke liye critical hai.
Jab ek component remove hota hai (conditional render, route change, etc.), React saari cleanup functions run karta hai β useEffect cleanup, phir useLayoutEffect cleanup. DOM nodes document se remove ho jaate hain.
Empty deps array: mount ke baad ek baar run karta hai. Cleanup unmount par run hoti hai. componentDidMount + componentWillUnmount ke equivalent.
Mount ke baad aur jab bhi dep change ho tab run karta hai. Cleanup har re-run se pehle aur unmount par run hoti hai.
Koi deps array nahi: har render ke baad run karta hai. Kab hi aap yahi chahte hain β state changes trigger karne par infinite loops cause karta hai.
useEffect jaisa hi signature lekin DOM mutations ke baad, paint se pehle synchronously fire hota hai. DOM measurements ke liye use karein.
useEffect callback se return ki gayi function. React ise next effect run se pehle aur unmount par call karta hai.
1function Component({ userId }) {2 const [data, setData] = useState(null);34 useEffect(() => {5 // Runs after mount and when userId changes6 let cancelled = false;78 fetch(`/api/user/${userId}`)9 .then(res => res.json())10 .then(json => {11 if (!cancelled) setData(json); // guard against stale closure12 });1314 // Cleanup: cancel if userId changes before fetch resolves15 return () => { cancelled = true; };16 }, [userId]); // re-runs when userId changes1718 // Runs on unmount19 useEffect(() => {20 return () => console.log('Component unmounted');21 }, []);22}
Lifecycle timing samajhna sabse common React bugs rokta hai: cleanup ke bina data fetch karna (unmounted component par setState warnings cause karta hai), timers clear karna bhool jaana (memory leaks cause karta hai), aur dependency array ka galat use karke effects bahut zyada ya bahut kam chalana.
A user profile page fetches user data on mount. If a user rapidly clicks through profiles (User A β User B β User C), the displayed data sometimes shows User A's data on User C's page.
Each navigation triggers a re-mount with a new userId. The useEffect fires 3 fetch calls, but they resolve out of order: User B (fast) β User C (fast) β User A (slow). The last-resolving fetch (User A) overwrites the correct data.
Use the cleanup function to set a `cancelled` flag. When userId changes, the previous effect's cleanup runs before the new effect, marking the old fetch as stale. The guard `if (!cancelled) setData(json)` prevents stale responses from updating state.
Takeaway: The cleanup function in useEffect isn't just for unmounting β it runs before EVERY re-execution of the effect. This makes it the perfect place to cancel async operations and prevent race conditions.
A chart component adds a `window.resize` event listener on mount to recalculate dimensions. After navigating away, the browser's memory usage keeps climbing and console shows 'setState on unmounted component' warnings.
The event listener was added in useEffect but never cleaned up. The component unmounts, but the listener still holds a reference to the component's state setter, creating a memory leak and triggering warnings on resize.
Return a cleanup function from useEffect that removes the event listener. The cleanup runs during the Unmount phase, before DOM removal, ensuring no orphaned listeners persist. Apply the same pattern for WebSocket connections, interval timers, and IntersectionObserver instances.
Takeaway: Every subscription, listener, or timer created in useEffect MUST have a corresponding cleanup. Think of mount/unmount as a pair: every 'set up' action needs a corresponding 'tear down' action.