0% found this document useful (0 votes)
7 views5 pages

REACTLIFECYCLE

The document explains React lifecycle methods in class components, detailing the three main phases: Mounting, Updating, and Unmounting, along with their respective methods. It introduces React Hooks, which allow functional components to manage state and lifecycle events, highlighting useState and useEffect as replacements for class-based lifecycle methods. The document emphasizes the advantages of using Hooks for new projects due to their simplicity and flexibility over traditional class components.

Uploaded by

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

REACTLIFECYCLE

The document explains React lifecycle methods in class components, detailing the three main phases: Mounting, Updating, and Unmounting, along with their respective methods. It introduces React Hooks, which allow functional components to manage state and lifecycle events, highlighting useState and useEffect as replacements for class-based lifecycle methods. The document emphasizes the advantages of using Hooks for new projects due to their simplicity and flexibility over traditional class components.

Uploaded by

Shriya Sridhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

React Lifecycle Methods in Class Components

Before Hooks, React components used classes to manage state and lifecycle events. Every

class component in React goes through a lifecycle that consists of three main phases:

1.Mounting: When the component is being created and inserted into the DOM.

2.Updating: When the component is being re-rendered due to changes in props or state.

3.Unmounting: When the component is being removed from the DOM.

Mounting Phase

During the mounting phase, the component is created and added to the DOM. React provides

the following lifecycle methods for this phase:

•constructor(): This is the first method that runs in a component’s lifecycle. It is mainly

used for initializing state or binding event handlers.

•componentDidMount(): Called immediately after the component is mounted. It’s often

used for fetching data from an API or interacting with the DOM.

class MyComponent extends React.Component {


constructor(props) {
super(props);
this.state = { data: null };
}
componentDidMount() {
// Fetch data when the component mounts
fetch('/api/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return <div>{this.state.data ? this.state.data : "Loading..."}</div>;
}
}

Updating Phase

In the updating phase, a component re-renders in response to changes in state or props. The

following lifecycle methods are available:

•componentDidUpdate(prevProps, prevState): This method is called after a

component has updated. It allows you to perform actions after the component has been re-

rendered, such as updating the DOM or making new API requests.

componentDidUpdate(prevProps, prevState) {

if (prevState.data !== this.state.data) {

console.log('Data has been updated!');

Unmounting Phase

The unmounting phase occurs when the component is removed from the DOM. The only

lifecycle method available in this phase is:


•componentWillUnmount(): This method is called right before a component is removed

from the DOM. It’s useful for cleaning up resources like timers or event listeners.

componentWillUnmount() {

clearInterval(this.timer);

React Hooks: A Functional Approach to Lifecycle Management

React Hooks, introduced in React 16.8, allow functional components to manage state and

lifecycle events, eliminating the need for class components in most cases. The two most

essential hooks that replace lifecycle methods are useState and useEffect.

useState: Managing State in Functional Components

The useState Hook allows you to add state to functional components. It returns an array

containing the current state value and a function to update it.

Example:

import React, { useState } from 'react';

function Counter() {

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

return (

<div>

<p>You clicked {count} times</p>

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

Click me

</button>

</div>
);

export default Counter;

Here, useState(0) initializes the state variable count with a value of 0. The setCount function is

used to update the state whenever the button is clicked.

useEffect: Handling Side Effects

The useEffect Hook serves the same purpose as lifecycle methods

like componentDidMount, componentDidUpdate, and componentWillUnmount. It allows you to

perform side effects, such as data fetching or interacting with the DOM, in functional

components.

Example:

import React, { useState, useEffect } from 'react';


function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
// Fetch data on component mount
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data));
// Cleanup on unmount
return () => console.log('Cleanup');
}, []); // Empty dependency array to run only on mount and unmount
return <div>{data ? data : "Loading..."}</div>;
}
export default DataFetcher;

In this example:

•The useEffect Hook is used to fetch data when the component mounts.

•The empty dependency array ([]) ensures the effect only runs on mount and unmount.
•The cleanup function (return () => console.log('Cleanup'))

mimics componentWillUnmount.

Key Differences Between Lifecycle Methods and Hooks

1.Class Components vs. Functional Components:

Lifecycle methods are exclusive to class components, while Hooks bring similar

functionality to functional components.

2.Multiple Effects:

With Hooks, you can have multiple useEffect calls to handle different side effects, whereas

lifecycle methods combine everything into a single method (e.g., componentDidMount for

all initialization logic).

3.Simplified Code:

Hooks allow for more concise and readable code compared to lifecycle methods, especially

when handling state and side effects in smaller, focused chunks.

4.No Need for this:

Class components require binding this to access state and props, which can lead to

confusion. Hooks eliminate this issue, making functional components easier to work with.

When to Use Lifecycle Methods vs. Hooks

React encourages developers to use Hooks over class components for new projects due to their

simplicity and flexibility. However, you may still encounter class components in legacy

codebases, and understanding lifecycle methods is essential for maintaining such projects.

For new projects:

•Use Hooks for managing state and side effects in functional components.

•Use Lifecycle Methods in class components only if you’re working with older codebases

that haven’t migrated to Hooks.

React lifecycle methods and Hooks are fundamental concepts for managing a component’s

state and side effects throughout its existence. While class components rely on lifecycle

methods to handle various phases, Hooks provide a more modern, functional approach that

simplifies state management and side effects.

You might also like