componentDidUpdate() is a React lifecycle method that runs immediately after a component’s updates are applied to the DOM. It is useful for performing actions that depend on updated props or state.
- Fetch new data when props or state change.
- Update external APIs or trigger side-effects after updates.
- Perform DOM manipulations based on updated values.
- Log changes or track component updates for debugging.
Syntax:
componentDidUpdate(prevProps, prevState, snapshot) { /
/ Your code here
}
- prevProps: This parameter contains the props that the component had before the update.
- prevState: This parameter contains the state of the component before the update.
- snapshot(optional): This is rarely used but they return value using the getSnapshotBeforeUpdate() method.
Time to Call componentDidUpdate()
componentDidUpdate() is called after the component’s updates are flushed to the DOM. This typically happens
- When the component’s props or state has changed, causing a re-render.
- After React applies these updates to the DOM and ensures the user sees the new UI.
- As a phase to handle side-effects that rely on the updated DOM or new state values.
It’s important to note that componentDidUpdate() is part of the React class component lifecycle. In modern React applications, functional components with hooks (like useEffect()) are more commonly used, offering a similar post-update side-effect capability.
Implementing componentDidUpdate() Method
It Use this method to perform actions after a component updates, such as fetching data, updating the DOM, logging changes, or triggering side-effects based on new props or state.
Tracking Scroll Position
The user scroll position and updates the component state. If the user scrolls past a certain threshold, the component can trigger additional actions or display messages.
import React, { Component } from "react";
class ScrollTracker extends Component {
state = { scrollPosition: 0 };
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.scrollPosition !== prevState.scrollPosition) {
console.log(`Scroll position updated: ${this.state.scrollPosition}px`);
if (this.state.scrollPosition > 300) {
console.log("You've scrolled past 300px!");
}
}
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
handleScroll = () => {
this.setState({ scrollPosition: window.scrollY });
};
render() {
return (
<div>
<h1>Scroll down and check the console</h1>
<p style={{ height: "1500px" }}>Keep scrolling...</p>
</div>
);
}
}
export default ScrollTracker;
Output: