![]() |
VOOZH | about |
The React component lifecycle describes the different stages a component goes through, allowing code to run at specific moments during its existence.
Here are the three main phases of the React component lifecycle:
React components follow a well-defined sequence of stages that determine how they are initialized, rendered to the DOM, updated when state or props change, and finally removed from the interface during their lifecycle.
Mounting refers to the process of creating and inserting a component into the DOM for the first time in a React application. During mounting, React initializes the component, sets up its internal state (if any), and inserts it into the DOM.
constructor()
Method to initialize state and bind methods. Executed before the component is mounted.
constructor(props) {
super(props); // Always call super(props) before using this.props
this.state = {
count: 0, // Initial state
};
console.log("Constructor called");
}getDerivedStateFromProps(props, state)
Used for updating the state based on props. Executed before every render.
static getDerivedStateFromProps(props, state) {
if (props.value !== state.value) {
return { value: props.value }; // Update state based on new props
}
return null; // No changes to state
}render() method
Responsible for rendering JSX and updating the DOM.
render() {
return (
<div>
<h1>Hello, React Lifecycle!</h1>
</div>
);
}componentDidMount() Function
This function is invoked right after the component is mounted on the DOM, i.e. this function gets invoked once after the render() function is executed for the first time.
componentDidMount() {
console.log("Component has been mounted");
// Example: Fetch data from an API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => this.setState({ data }));
}Updating is the phase where a component re-renders in response to changes in its state or props, ensuring the UI reflects the latest data.
getDerivedStateFromProps()
getDerivedStateFromProps(props, state) is a static method that is called just before the render() method in both the mounting and updating phase in React. It takes updated props and the current state as arguments.
static getDerivedStateFromProps(props, state) {
if (props.name !== state.name) {
return { name: props.name }; // Update state with new props
}
return null; // No state change
}nullsetState()
This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the state of a component.
this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));shouldComponentUpdate()
shouldComponentUpdate() is a React class lifecycle method that controls whether a component re-renders by comparing current and next props or state and returning true or false.
shouldComponentUpdate(nextProps, nextState)It returns true or false, if false, then render(), componentWillUpdate(), and componentDidUpdate() method does not get invoked.
getSnapshotBeforeUpdate()
The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated.
getSnapshotBeforeUpdate(prevProps, prevState)componentDidUpdate()
Similarly, this function is invoked after the component is rendered, i.e., this function gets invoked once after the render() function is executed after the updation of State or Props.
componentDidUpdate(prevProps, prevState, snapshot)This is the final phase of the lifecycle of the component, which is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.
componentWillUnmount()
This function is invoked before the component is finally unmounted from the DOM, i.e., this function gets invoked once before the component is removed from the page, and this denotes the end of the lifecycle.
Implementing component lifecycle methods allows developers to control a React componentās behavior at different stages such as mounting, updating, and unmounting.
Create a react app and edit your index.js file from the src folder.
Output:
š React lifecycle example - output
Here are some methods:
It provides a structured way to handle specific tasks at various points in a componentās life, such as when it is created, updated, or destroyed.
Functional components use hooks for simpler, cleaner state and side-effect management, while class components rely on multiple lifecycle methods, making them more complex.
Class Components | Functional Components |
|---|---|
State initialized using constructor() | State managed using useState() |
Uses lifecycle methods like componentDidMount(), componentDidUpdate(), componentWillUnmount() | Uses useEffect() for lifecycle handling |
Updates handled with shouldComponentUpdate() and componentDidUpdate() | Updates handled using useEffect() dependency array |
Cleanup done in componentWillUnmount() | Cleanup returned from useEffect() |
Logic tied to lifecycle methods | Uses hooks like useState, useEffect, useCallback, useMemo |