React Lifecycle Methods
In React, lifecycle methods are hooks available in class components that allow you to run code at specific points in a component's lifecycle. These methods provide hooks for managing side effects, initializing data, and cleaning up resources. Here’s a summary of the key lifecycle methods:
1. Mounting:
When a component is being created and inserted into the DOM.
-
constructor(props)
: Initializes the component's state and binds methods. It's called before the component is mounted. -
static getDerivedStateFromProps(nextProps, prevState)
: Invoked right before rendering, both on the initial mount and on subsequent updates. It can return an object to update the state ornull
to do nothing. -
render()
: The core method that returns the JSX to render. It should be a pure function, returning the same output for the same props and state. -
componentDidMount()
: Invoked immediately after a component is mounted. Ideal for making network requests, initializing third-party libraries, or setting up subscriptions.
2. Updating:
When a component is being re-rendered as a result of changes to either its props or state.
-
static getDerivedStateFromProps(nextProps, prevState)
: (Already mentioned under Mounting) -
shouldComponentUpdate(nextProps, nextState)
: Determines if the component should re-render. By default, it returnstrue
. It’s used for performance optimization. -
render()
: (Already mentioned under Mounting) -
getSnapshotBeforeUpdate(prevProps, prevState)
: Invoked right before the most recently rendered output is committed to the DOM. It can capture information (e.g., scroll position) from the DOM before it is potentially changed. -
componentDidUpdate(prevProps, prevState, snapshot)
: Invoked immediately after updating occurs. It can be used for operations like network requests in response to prop or state changes. Thesnapshot
argument comes fromgetSnapshotBeforeUpdate
.
3. Unmounting:
When a component is being removed from the DOM.
componentWillUnmount()
: Invoked immediately before a component is unmounted and destroyed. It’s used for cleanup tasks like invalidating timers, cancelling network requests, or cleaning up subscriptions.
4. Error Handling:
When there’s an error during rendering, in a lifecycle method, or in the constructor of any child component.
-
static getDerivedStateFromError(error)
: Invoked when an error is thrown during rendering. It allows you to update the state to display an error message. -
componentDidCatch(error, info)
: Invoked when an error is thrown. It can be used to log error information or perform error handling.
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { data: null };
}
static getDerivedStateFromProps(nextProps, prevState) {
// Update state based on props
if (nextProps.someValue !== prevState.data) {
return { data: nextProps.someValue };
}
return null;
}
componentDidMount() {
// Fetch data or setup
fetchData().then(data => this.setState({ data }));
}
shouldComponentUpdate(nextProps, nextState) {
// Prevent re-render if data hasn't changed
return nextState.data !== this.state.data;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Capture DOM info before the update
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// Handle updates
}
componentWillUnmount() {
// Cleanup
}
render() {
return <div>{this.state.data}</div>;
}
}
export default MyComponent;