In React, class-based components play a crucial role in managing the rendering, updating, and unmounting of UI components. functional components with hooks are now the preferred way of writing React components.
class-based components in React were the traditional way to define components prior to the introduction of function components and Hooks in React 16.8.Although function components with Hooks are now preferred for their simplicity and flexibility, class components are still widely used in legacy codebases. understanding class components is essential for working with older react project.
The lifecycle of a class-based component in React consists of different phases during which specific methods are called to handle various operations like initialization, rendering, updating, and unmounting.
React speed comes from its two main phases: the render and commit phases. During the render phase, the constructor is invoked first, followed by the render( ) method. In the commit phase, react updates the DOM and then triggers the componenDidMount( ) method.
Phases of a Class-Based Component Lifecycle
1.Mounting (Creating a component)
2.Updating (When props or state change)
3. Unmounting (Cleaning up the component)
1. Mounting Phase (Component Creation) :
The mounting phase occurs when the component is being created and inserted into the DOM.
The constructor( ) lifeCycle method
The constructor is the first method called when the component is created. It’s primarily used for: Initializing the component’s state. and bind event handlers, the constructor is the first method invoked when an instance of the component is created.
The constructor function is used to:
- Initialize local state or any other third-party libraries.
- Bonding event handlers the instance
some points to keep in mind about constructor:
- Every component need not include a constructor.
- To set property or use “this” we need to call super( ) within constructor.
Example
class mycomponent extends React.Component { constructor(props){ super(props)://ALWAYS CALLS super(props) when using class based components to access the super class methods and this.state={ count:1 }; } }
The Render( ) lifecycle method
The render method is responsible to rendering components to DOM based on its current props and state its is called every time when components to be re- render, the Render() method must return the piece of JSX representing the components structure ,This is the method where the components is displayed in browser.
Example
render(){ return( <div className="use-cart"> <h1>NAME={this.state.info.name}</h1> <h2>LOCATION={this.state.info.location}</h2> <h2>CONTACT={this.state.info.email</h2> <img className="pic" src={this.state.info.avatar_URL}/> </div> ); }
The ComponentDidMount( ) lifecycle method
- ComponentDidMount( ) method is called immediately after the component is inserted into the DOM , ComponentDidMout( ) is mainly used to set up any necessary event listeners or timers,perform any necessary API calls or data fetching and DOM manipulations ,
- Fetching Data from an API: componentDidMount() is used to make an HTTP request or API call to fetch data. Since it’s called after the initial render, it ensures that the component has been inserted into the DOM before attempting to fetch data.
Example:
import React from "react"; class UserClass extends React.Component { constructor(props) { super(props); this.state= { info:{ name: "FIROJ", location:"warangle", avatar_url:"httpvjkjhvc" }} async componentDidMount() { const data= await fetch("https://api.github.com/users/RIYAZ12697"); const json= await data.json(); console.log(json); this.setState({ info:json }); } render() { return( <div className="user-cart"> <h2> NAME: {this.state.info.name}</h2> <h2> LOCATION: {this.state.info.location}</h2> <h2> CONTACT: [email protected]</h2> <img className="pic" src={this.state.info.avatar_url}/> </div> ); } } export default UserClass;
Updating phase(When props or state change)
- This phase occurs whenever there is change to the component’s props or state during this phase the React re-renders the component to reflect the new state or props.
Triggers for the updating phase:
- State Changes: When the component’s state is updated using this.setState.
- Props Changes: When the parent component passes new props to the child component.
The shouldComponentUpdate() lifecycle method
- The shouldComponentUpdate() method is called before a component is updated.
- It takes two arguments: nextProps and nextState. This method returns a boolean value that determines whether the component should update or not. If this method returns true, the component will update, and if it returns false, the component will not update.The shouldComponentUpdate method provides a way to optimize performance by skipping unnecessary renders.
Example:
shouldComponentUpdate(nextProps, nextState)
{
return nextProps.value !== this.props.value;
The Render( ) lifecycle method
- The render phase focuses solely on producing the new virtual DOM representation based on updated state or props. The render phase is distinct from the actual DOM updates (known as the commit phase
- This is the method that is responsible for inserting a Component into the DOM. This is invoked every time a Component’s state/props is updated.
- React compares the newly generated virtual DOM tree with the previous one (diffing algorithm).Based on the comparison, React identifies the minimal set of changes needed to update the actual DOM.
Example:
import React { Component } from “react”;
class Counter extends Component { constructor(props) { super(props); this.state = { count: 0, }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; shouldComponentUpdate(nextProps, nextState) { return nextState.count % 2 === 0; } render() { console.log("Render method called!"); return ( <div> <h1>Count: {this.state.count}</h1> <button onClick={this.increment}>Increment</button> </div> ); } } export default Counter
The componentDidUpdate() lifecycle method
- The componentDidUpdate() method is a lifecycle method in React that is called after a component has been updated and re-rendered. It is useful for performing side effects or additional operations when the component’s props or state have changed.
It allows you to perform side effects, such as
- Logging.
- Fetching data based on new props or state.
- Interacting with the DOM.
Key Arguments of componentDidUpdate
When componentDidUpdate is executed, it provides two arguments:
- prevProps: The props the component had before the update.
- prevState: The state the component had before the update.
This allows you to compare the previous values with the current ones to decide if some action is necessary.
Example:
import React { Component } from "react"; class Counter extends Component { constructor(props) { super(props); this.state = { count: 0, }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { console.log(`Count changed from ${prevState.count} to ${this.state.count}`); } } render() { return ( <div> <h1>Count: {this.state.count} </h1> <button onclick={this.increment}Increment </button> </div> ); } } export default Counter;
Unmounting Phase
- The unmounting phase refers to the lifecycle stage when a component is being removed from the DOM (Document Object Model) and is no longer rendered or accessible.
- During this phase, React performs a series of cleanup operations to ensure that the component and its associated resources are properly disposed of.
- The unmounting phase is the last stage in the lifecycle of a React component and occurs when the component is being removed from the DOM tree.
The componentWillUnmount() lifecycle method
This method is called just before the component is removed from the DOM. It allows you to perform any necessary cleanup, such as canceling timers, removing event listeners, or clearing any data structures that were set up during the mounting phase.
After componentWillUnmount() is called, the component is removed from the DOM and all of its state and props are destroyed.
It’s important to note that once a component is unmounted, it cannot be mounted again. If you need to render the component again, you will need to create a new instance of it.
It allows you to clean up resources such as:
- Canceling network requests.
- Clearing timers or intervals.
- Removing event listeners.
- Cleaning up subscriptions
Example:
import React from "react"; class UserClass extends React.Component{ constructor(props){ super(props); this.state={ info:{ name: "fffff", location:"warangle", avatar_url:"httpvjkjhvc" }} } async componentDidMount(){ const data= await fetch("https://api.github.com/users/RIYAZ12697"); const json= await data.json(); console.log(json); this.setState({ info:json }); this.timer =setInterval(()=> { console.log("nmaste react"); },1000); } componentDidUpdate(){ console.log("called in update phase"); } componentWillUnmount() { clearInterval(this.timer) } render() { return( <div className="user-cart"> <h2> NAME: {this.state.info.name}</h2> <h2> LOCATION: {this.state.info.location}</h2> <h2> CONTACT: [email protected]</h2> <img className="pic" src={this.state.info.avatar_url}/> </div> ); } } export default UserClass;
Conclusion :
The lifecycle of class-based components in React provides a structured way to manage and respond to different stages of a component’s existence. From initial rendering to updating and finally unmounting, these lifecycle methods give developers fine-grained control over their components. The lifecycle methods of class-based components remain essential for handling tasks like fetching data, updating the UI based on state or props, and cleaning up before unmounting. Although function components with Hooks are the modern approach, understanding class component lifecycle methods is still crucial for working with older codebases and for a deeper understanding of how React operates.