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.
माउंट, अपडेट और अनमाउंट चरण — देखें कि हर चरण में कौन से hooks और effects चलते हैं।
हर React component तीन lifecycle phases से गुज़रता है: Mount (DOM में पहला render), Update (state या prop changes के कारण re-renders), और Unmount (DOM से हटाना)। Hooks के साथ, ये phases class lifecycle methods के बजाय useEffect, useLayoutEffect, और cleanup functions के माध्यम से व्यक्त होती हैं।
React आपका function component call करता है, JSX evaluate करता है, और resulting DOM nodes insert करता है। useState initializers चलते हैं, useRef objects बनते हैं। DOM insertion के बाद, useLayoutEffect synchronously चलता है, फिर useEffect paint के बाद asynchronously चलता है।
जब setState या एक नया prop आता है, React एक re-render queue करता है। Re-render के दौरान, hooks उसी order में call होते हैं जैसे mount पर। React नए vs पुराने output को compare करता है और DOM को patch करता है। Effects को फिर से चलाने से पहले, React पिछले render के effects से cleanup functions चलाता है।
प्रत्येक effect के फिर से चलने से पहले (और unmount पर), React पिछले effect की cleanup function call करता है। यह timers clear करने, fetches cancel करने, और events से unsubscribe करने के लिए crucial है।
जब एक component हटाया जाता है (conditional render, route change, आदि), React सभी cleanup functions चलाता है — useEffect cleanup, फिर useLayoutEffect cleanup। DOM nodes document से remove होते हैं।
Empty deps array: mount के बाद एक बार चलता है। Cleanup unmount पर चलती है। componentDidMount + componentWillUnmount के equivalent।
Mount के बाद AND जब भी dep बदलता है तब चलता है। Cleanup प्रत्येक re-run से पहले और unmount पर चलती है।
No deps array: हर render के बाद चलता है। शायद ही कभी यही चाहते हैं — यदि state changes trigger करता है तो infinite loops का कारण बनता है।
useEffect के समान signature लेकिन DOM mutations के बाद, paint से पहले synchronously fire होता है। DOM measurements के लिए उपयोग करें।
useEffect callback से return होने वाला function। React इसे अगले effect run से पहले और unmount पर call करता है।
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 को समझना सबसे common React bugs को prevent करता है: cleanup के बिना data fetching (unmounted component पर setState warnings का कारण), timers clear करना भूलना (memory leaks का कारण), और dependency array के गलत उपयोग से effects को बहुत बार या बहुत कम चलाना।
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.