LifeCycle Component Overview

React components are built, added, updated, and destroyed. Callback APIs or lifecycle hooks let React developers run code and interact with components at specific times. These tactics are essential for creating dynamic, interactive, and powerful online apps.
The term “state” in React describes a structure that records the way data in your application changes over time. Because it enables you to create dynamic web apps and interactive components, managing state is an essential React skill. State can be used to capture dynamic data from an API or to track form inputs. This lesson will walk you through an example of class-based component state management.
The existence of a React component can be divided into three phases:
Mounting: Mounting involves creating and inserting DOM components. To run code and communicate with your component at various stages of its lifecycle, utilise lifecycle methods. The Mounting, Updating, and Unmounting components form the basis of these techniques.
Updating: DOM component removal. The process by which a component re-renders itself and its corresponding user interface to reflect modifications in its data is referred to as updating in React. When creating dynamic web apps that react to user interaction or fresh data, this is an essential component.
Unmounting: React components’ final stage is unmounting, which removes them from the DOM. Cleanup activities to prevent memory leaks and optimise application performance are essential at this period. This stage’s main lifecycle function is componentWillUnmount(), called before the component is unmounted.
Class components which explicitly implement these lifecycle methods were the core React component definition before. Since 16.8, React Hooks let functional components manage state and lifecycle aspects, resulting in shorter, clearer code.
Component Lifecycle Methods (Class Components)
Throughout the lifecycle of class-based components, multiple unique methods are called. The several phases a component goes through from creation to removal from the DOM are referred to as the component lifecycle in React. These phases can be roughly divided into three categories: mounting, updating, and unmounting. Internal state and a wide range of lifecycle methods are supported by class components, which are ES6 classes that extend React.Component.
Mounting Phase
Upon initialising and rendering a component for the first time, these methods are called sequentially. The rendering of a React component into the Document Object Model (DOM) for the first time is known as the mounting phase in React. In the lifecycle of a component, which also includes updating and unmounting, this is one of the discrete phases. A certain order of lifecycle methods is called while creating a component.
constructor(props):
Purpose: Upon creating a component instance, this function is the first one called. An object is assigned to this.state to initialise local state, and event handler functions are bound to the component instance.
Key points: Avoid causing subscriptions or side effects in the constructor. Here, this.state is assigned directly; nevertheless, this.setState() shouldn’t be invoked.
static getDerivedStateFromProps(props, state):
Purpose: This static method is called on both the first mount and any changes that follow, immediately before render(). Its main function is to synchronise state with props when the state must adapt to changes in the props. It should return null to show that no state change is required, or an object to update the state.
Key points: This is not accessible to it because it is static. There should be no adverse effects, hence it should be a pure function.
Render():
Purpose: This is the only function that a class component has to have. It returns browser-visible JSX (React components). The goal of React is to ease web application UI development. It does this by providing a JavaScript library that improves declarative code, efficiency, flexibility, and developer experience.
Execution: It’s called after the constructor (or getDerivedStateFromProps) and recalled if states or props change.
Key points: the state and props of the component should be the only parameters used by render(). It shouldn’t use the DOM, change component state, or make API calls.
ComponentDidMount():
Purpose: This function is called right away upon the component’s mounting (insertion) into the DOM. Doing activities that need the component to be in the DOM is best done there.
Common uses:
- Requesting information from an API or using AJAX.
- Establishing subscriptions (such as event listeners or timers like setInterval).
- Altering the DOM directly (if required).
- Compatibility with additional JavaScript frameworks.
Key points: This should handle AJAX requests and DOM/state modifications. This method is utilised for integrating with JavaScript frameworks and functions having delayed execution, such as setTimeout or setInterval. We use it to update state and activate lifecycle methods.
Updating Phase
The Updating Phase in React involves a component re-rendering and updating its user interface in response to internal state or external prop changes. Interactive web apps require this dynamic behaviour.
React uses a reconciliation cycle to decide the best approach to update the Document Object Model when a component’s state or props change. This technique compares a new virtual DOM tree, which reflects the updated application state, to the old one and calculates the least number of operations needed to change it.
static getDerivedStateFromProps(props, state):
Purpose: In order to update state in response to prop changes, this function is also called during the updating phase, before to render(), as previously described.
shouldComponentUpdate(nextProps, nextState):
Purpose: The goal is to call this method before re-rendering if new state or props are received. It gives back a true or false boolean result that tells React whether to continue with the re-rendering.
Performance Optimization: By returning false, you can improve application speed by avoiding needless re-renderings of a component and its children. In order to avoid minor problems involving mutable state or props, it always returns true by default.
Alternatives: React.PureComponent (for class components) and React.memo (for functional components) are substitutes that offer a simple method of optimising pure components by automatically implementing a shallow comparison for props and state in shouldComponentUpdate.
getSnapshotBeforeUpdate(prevProps, prevState):
Purpose: This method’s goal is to be called just prior to the latest rendered output being committed to the DOM. Prior to applying the possible modifications, it enables the component to retrieve certain data from the DOM, such as the scroll position. This method returns a value that is supplied to componentDidUpdate() as the snapshot argument.
componentDidUpdate(prevProps, prevState, snapshot):
Purpose: This function is called right after updating, which indicates that the DOM has been updated and the component has been re-rendered.
Common uses: Typical applications include requesting new data when a userId prop changes and executing DOM activities following an update and submitting network requests based on prop or state changes.
Key points: Unlike componentDidMount, this function accepts prevProps and prevState as parameters (as well as the snapshot from getSnapshotBeforeUpdate). This enables comparison with the state and current props to determine whether to do an action.
Unmounting Phase
This function is called before DOM component deletion. The useEffect Hook in functional components combines componentDidMount, componentDidUpdate, and componentWillUnmount into one API. It lets the useEffect Hook return a method to clean up when the component unmounts. This provides responsible release when the component is no longer needed.
componentWillUnmount():
Purpose: It is used before unmounting and discarding a component. Cleanup after unnecessary subscriptions and memory leaks requires it.
Common cleanup tasks:
- Timers (like clearInterval) are being invalidated.
- Blocking requests from the network.
- Event listeners that were manually added to the document or window are being removed.
- Any subscriptions or Redux states should be cleaned.
Component Lifecycle Methods
Existing “stateless” functions couldn’t use lifecycle methods or control their state before React 16.8. Functions can leverage state and lifecycle events using React Hooks. Hooks are broadly used to run custom routines when component props change. Hooks allow developers to write simpler, more readable, and easier-to-share and maintain code without using classes for state management. Hooks differ from class-based state management because no object holds all state. You can split state into various sections and update them separately.
UseState and useEffect are the main Hooks for handling state and side effects that address lifecycle issues.
UseState()
Purpose: Its purpose is to enable the declaration of state variables by functional components. The value of the current state and a function to update it are the two things it returns.
Key points: Not like this.SetState in class components and useState setters require manual object state update merging; they do not automatically merge objects.
useEffect(lifeCycleFunction, dependencyArray):
Purpose: Performing side effects in functional components is the goal of this hook. The componentDidMount, componentDidUpdate, and componentWillUnmount features from class components are combined into a single API.
Parameters:
- ExecuteFn, also known as lifeCycleFunction, is the function that houses the side effect logic. This function automatically executes after each render.
- When the lifeCycleFunction reruns, it is controlled by the optional dependencyArray (values).
Empty array ([]): The effect removes itself when the component unmounts and runs once following the initial render. ComponentDidMount and componentWillUnmount added together are the same as this.
Array with values ([prop1, state2]): Only if there are any changes in the array’s value between renderings does the effect rerun. The conditional logic componentDidUpdate is the same as this.
No dependency array: every render is followed by the effect, and cleaning (if it is returned) occurs before to each re-execution and unmount. Generally speaking, this is avoided unless it is absolutely necessary to rerun the effect on each render.
Cleanup Function: A cleanup function may be returned by the lifeCycleFunction. Memory leaks are avoided by having this method run before the component unmounts and before the effect reruns (if dependencies change).
Code Example:
The lifecycle methods will be demonstrated with a basic clock component that shows the current time and updates it every second.
import React, { useState, useEffect } from 'react';
function Clock() {
const [date, setDate] = useState(new Date());
useEffect(() => {
console.log("Clock :: Initialize :: useEffect :: Component mounted");
const intervalId = setInterval(() => {
setDate(new Date());
}, 1000);
return () => {
console.log("Clock :: Remove :: useEffect cleanup :: Component unmounted");
clearInterval(intervalId);
};
}, []);
return (
<div>
<p>The current time is {date.toLocaleTimeString()}</p>
</div>
);
}
export default Clock;
Important Considerations and Best Practices
State Management: State is a controlled internal object that contains data that may change throughout the course of the component’s life. Props (properties) are read-only to convey data and methods between parent and child components. Since props are immutable, React replaces the old props and re-renders the component with the modified values if the parent alters a prop.
Performance Optimization: Optimising the speed of React applications requires avoiding pointless re-renders. methods such as React and shouldComponentUpdate in the class components.UseCallback, memo, and useMemo in functional components assist avoid expensive recalculations when state or props have not changed.
Side Effects and Data Fetching: Functional components should utilise useEffect for asynchronous actions like accessing Web APIs and class components componentDidMount. This avoids establishing state on unmounted components and ensures they are mounted and ready to receive data.
Cleanup: Cleaning up After component removal. Clear out timers and event listeners started during mounting to avoid memory leaks.
Separation of Concerns: Differentiating between presentational (data display) and container (data and logic management) components is smart. This encourages code reuse and maintenance.
Pure render() function: Render() should be a pure function that returns JSX from props and state without side effects.
Developers may create reliable, effective, and engaging React apps that react dynamically to user input and data changes by skilfully utilising these lifecycle methods and Hooks.