React Lifecycle Phases: Mounting, Updating, Unmounting

⚛️ Top 150 React Interview Questions – 42/150 📌 Topic: The 3 Phases of Lifecycle 🔹 WHAT is it? Every React component follows a Lifecycle, which means it goes through specific stages from creation to removal. There are 3 main phases: Mounting → Component is created and added to the DOM Updating → Component re-renders due to props or state change Unmounting → Component is removed from the DOM 🔹 WHY is it designed this way? React uses lifecycle phases to manage timing, performance, and memory. Timing Control: Some tasks (like API calls) should run only once, not on every render. Performance: React updates the UI only when props or state actually change. Memory Safety: Unmounting gives a safe place to clean up timers, listeners, and subscriptions. 🔹 HOW do you do it? (The Implementation) In modern React, all three phases are handled using useEffect. useEffect(() => { // 1️⃣ Mounting logic console.log("Component Born (Mounting)"); const timer = setInterval(() => { console.log("Tick"); }, 1000); // 3️⃣ Unmounting logic (Cleanup) return () => { console.log("Component Dying (Unmounting)"); clearInterval(timer); }; }, [count]); // 2️⃣ Updating: runs again when 'count' changes Empty dependency [] → runs only once (Mounting) Dependency [count] → runs on update return () => {} → runs on Unmounting 🔹 WHERE are the best practices? When to Use: Mounting → API calls, subscriptions Updating → syncing data, reacting to prop/state changes Unmounting → clearing timers & event listeners Avoid Side Effects in Render: Never fetch data or run logic directly in the component body. Correct Dependencies: Wrong dependency arrays can cause infinite loops or missed updates. 📝 Summary for your notes Socho component ek Employee hai 👇 Mounting → Joining day (setup & induction) Updating → Work changes based on new instructions Unmounting → Resignation day (cleanup & handover) 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #LearningInPublic #Top150ReactQuestions

  • text

To view or add a comment, sign in

Explore content categories