0% found this document useful (0 votes)
3 views14 pages

Module 4 - Lifecycle Methods & React Lifecycle

The document explains the lifecycle of React components, which consists of three phases: Mounting, Updating, and Unmounting. It highlights the importance of lifecycle management for tasks like fetching data, starting/stopping timers, and cleaning up resources. Additionally, it covers the use of the useEffect hook in functional components and compares it with lifecycle methods in class components, providing best practices and practical tasks for implementation.

Uploaded by

kkuldeep162j
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Module 4 - Lifecycle Methods & React Lifecycle

The document explains the lifecycle of React components, which consists of three phases: Mounting, Updating, and Unmounting. It highlights the importance of lifecycle management for tasks like fetching data, starting/stopping timers, and cleaning up resources. Additionally, it covers the use of the useEffect hook in functional components and compares it with lifecycle methods in class components, providing best practices and practical tasks for implementation.

Uploaded by

kkuldeep162j
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

______________________________________Module 4 – Lifecycle Methods & React Lifecycle

______________________________________

What is Lifecycle?

Every React component goes through different stages during its existence, just like a human
life.

Human Life Cycle

Birth

Childhood

Adult

Old Age

Death

React Component Life Cycle

Mounting

Updating

Unmounting

Every React component follows these three phases.

---

Real-Life Example

Imagine ordering food from Zomato 🍕

1. Order Placed → Mounting

2. Order Preparing & Tracking → Updating


3. Order Delivered → Unmounting

Similarly, a React component is:

Created

Updated whenever data changes

Removed when no longer needed

---

Why is Lifecycle Important?

Without lifecycle management, we cannot:

Fetch API data

Start timers

Stop timers

Listen to events

Clean up memory

Improve performance

Lifecycle helps React know what should happen at each stage.

---

Three Lifecycle Phases

1. Mounting Phase

Mounting means the component is created and inserted into the DOM for the first time.
Example:

<App />

When the page loads:

Component Created

HTML Generated

Displayed on Screen

---

Real-Life Example

Opening Instagram.

When the app opens:

Navbar appears

Feed loads

Stories appear

Everything is created for the first time.

This is Mounting.

---

Mounting in Functional Components

We use useEffect() with an empty dependency array.

import { useEffect } from "react";


function App() {

useEffect(() => {
[Link]("Component Mounted");
}, []);

return <h1>Hello React</h1>;


}

The empty array ([]) means the effect runs only once after the first render.

---

2. Updating Phase

Whenever State or Props change, React updates the component.

Example:

const [count, setCount] = useState(0);

Clicking the button changes the count:

Count = 0

Click

Count = 1

Component Updates

---

Example
import { useState } from "react";

function Counter(){

const [count,setCount]=useState(0);

return(

<>

<h1>{count}</h1>

<button onClick={()=>setCount(count+1)}>

Increase

</button>

</>

);

Every click causes the component to update.

---

Real-Life Example

Amazon Shopping Cart 🛒

Items = 2

Add one more item

Items = 3


Only the cart updates.

The whole page doesn't reload.

---

Updating with useEffect

import { useState, useEffect } from "react";

function Counter(){

const [count,setCount]=useState(0);

useEffect(()=>{

[Link]("Count Updated");

},[count]);

return(

<>
<h1>{count}</h1>

<button onClick={()=>setCount(count+1)}>
Increase
</button>

</>

);

Whenever count changes, the effect runs.

---

3. Unmounting Phase
Unmounting means removing a component from the screen.

Example:

Dashboard

Logout

Dashboard Removed

The component no longer exists.

---

Real-Life Example

Closing YouTube.

The video stops.

Timer stops.

Network requests stop.

Resources are cleaned up.

---

Cleanup Function

useEffect(()=>{

[Link]("Mounted");

return ()=>{

[Link]("Component Removed");
}

},[]);

The function returned from useEffect runs when the component unmounts.

---

Why Cleanup is Important

Without cleanup:

❌ Memory leaks

❌ Slow application

❌ Background timers keep running

❌ Event listeners remain active

---

Class Component Lifecycle

Before Hooks, React used lifecycle methods in class components.

Mounting

constructor()

render()

componentDidMount()

---

Updating
shouldComponentUpdate()

render()

componentDidUpdate()

---

Unmounting

componentWillUnmount()

---

Example (Class Component)

class App extends [Link]{

componentDidMount(){

[Link]("Mounted");

componentDidUpdate(){

[Link]("Updated");

componentWillUnmount(){

[Link]("Removed");

render(){
return <h1>Hello</h1>;

Today, these are mostly replaced by useEffect in functional components.

---

Functional vs Class Lifecycle

Class Component Functional Component

componentDidMount() useEffect(() => {}, [])


componentDidUpdate() useEffect(() => {}, [dependency])
componentWillUnmount() return cleanup function

---

Lifecycle Flow

Component Created

Render

Mount

State Changes

Update

Render Again

Component Removed

Cleanup

---

Common Mistakes

❌ Forgetting dependency array in useEffect.

❌ Not cleaning timers or event listeners.

❌ Updating state inside useEffect without proper dependencies, causing infinite loops.

❌ Using lifecycle methods in new functional components instead of Hooks.

---

Best Practices

Use useEffect for side effects only.

Always clean up timers, subscriptions, and event listeners.

Keep dependency arrays accurate.

Avoid unnecessary effects.

---

Practical Task
Build a Digital Clock.

Requirements:

Show current time.

Update every second using setInterval().

Stop the timer when the component unmounts using cleanup.

---

Assignment

Create a User Profile Component.

Features:

Display user information.

Log "Component Mounted" when it appears.

Log "User Updated" when the name changes.

Log "Component Unmounted" when it is removed.

Use useEffect() to manage all lifecycle behavior.

---

Interview Questions

1. What is the React Component Lifecycle?

2. What are the three lifecycle phases?

3. What is Mounting?
4. What is Updating?

5. What is Unmounting?

6. What is useEffect()?

7. Why do we use an empty dependency array ([])?

8. What is a cleanup function?

9. What causes a component to re-render?

10. What is the difference between componentDidMount() and useEffect()?

11. Why is cleanup important?

12. What is a memory leak?

13. What happens if you omit the dependency array?

14. Can useEffect run multiple times?

15. How do functional components replace lifecycle methods?

---

Mini Project – Live Weather Dashboard

Features
Fetch weather data when the component mounts.

Refresh data when the selected city changes.

Remove event listeners/timers during cleanup.

Show loading and error states.

Concepts Covered

React Lifecycle

useEffect

Mounting

Updating

Unmounting

Cleanup Functions

State Management

API Integration
_____________________________________

You might also like