React componentDidUpdate() Method [A Beginner's Guide]
Updated on Oct 28, 2024 | 13 min read | 18.4k views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 28, 2024 | 13 min read | 18.4k views
Share:
Table of Contents
React is a powerful view library that helps you build user interfaces. In addition to its stand-out functionalities, React also offers several methods that make development easier, including the ability to use components. Components are an integral part of React development that allows for breaking the user interface into smaller, more manageable chunks. Web development enthusiasts looking forward to mastering React must dive deep into React methods and component topics.
Out of the four built-in methods in React — constructor(), getDerivedStateFromProps(), render() and componentDidMount (), the componentDidUpdate() method is most commonly used in web development projects. This blog will look at how you can use the componentDidUpdate lifecycle method in React components. Also, we will dive deep into some of the benefits of using React componentDidUpdate and its examples.
Let's Start!
ComponentDidUpdate is a React component lifecycle method invoked immediately after a component's updates are flushed to the DOM. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.
However, this method is useful for setting states based on props changes or performing side-effects such as fetching data from an API. Also, you can use React hooks for functional components to achieve the same functionality.
componentDidUpdate(prevProps, prevState, snapshot)
Let’s define the parameters used in the componentDidUpdate function:
Take a look at an example of how componentDidUpdate is used to set the state based on the modifications made on props:
class MyComponent extends React. Component
{
componentDidUpdate(prevState, prevProps)
{
// Access props with this.props
// Access state with this.state
// prevState contains state before update
// prevProps contains props before update
}
render() {
return <div></div>;
}
}
Note that you should not call setState() in componentDidUpdate() hooks. Calling the setState() function will cause a rerender of the component and also lead to performance issues. If you need to set state based on props changes, use componentWillReceiveProps() instead. Assuming you need to work on something while the initial rendering, use the componentDidMount() function instead.
To learn more about React and know the flow of learning React from the start, you can check the React JS syllabus for our courses.
Medium
The React Component Did Update method gets called after a component has been updated. It is invoked immediately after updating occurs and not before. This means that even if you set the state in this method, it will not trigger another update,
There are several use cases for this lifecycle method:
There are a few situations where the componentDidUpdate capacity can be useful.
In this section, we’ll walk through the use of componentDidUpdate when working with DOM. We’ll get the component’s positioning, orientation, and dimensioning using DOM nodes. Also, we have an option to initialise an animation or pass the underlying DOM node to third-party non-React libraries.
Here, we will access the underlying DOM nodes of React components using this function. Let’s understand with the help of an example where the size the box will get updated every the "Resize" button is clicked:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { size: 100 };
this.boxRef = React.createRef();
}
handleIncrementClick = () => {
// set new state to force update
this.setState((state, props) => ({ size: state.size + 10 }));
};
componentDidUpdate(prevState, prevProps) {
// react to update and change the HTML element's size
this.boxRef.current.style.width = `${this.state.size}px`;
this.boxRef.current.style.height = `${this.state.size}px`;
}
render() {
return (
<div>
<button onClick={this.handleIncrementClick}>Resize</button>
<div ref={this.boxRef}></div>
</div>
);
}
}
Explanation
We have a component that acts as a storage house and keeps the record of the size value. On clicking the "Resize" button, the function handleIncrementClick increments the size by 10, and simultaneously the state is changed via the setState function. As a result, the component gets updated.
Note:
Every time the “Resize” button is clicked and the setState function is called, the componentDidUpdate function starts running, and the component gets updated. Also, you can use componentDidUpdate to get the ref to the div DOM element and adjust the basic dimensional properties like width and height.
The function componentDidUpdate is also helpful when fetching data from a server. That means you can use componentDidUpdate to fetch data from a targeted server or API
Let’s understand with the help of an example where we will pull data from a server. A user will have a list of projects, and the name of an individual user will be selected using buttons, while a list of user's projects will be fetched from a server.
In the parent MyComponent component, there are two buttons - one for selecting the name of the user and the other ProjectsComponent component to show the list of projects.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { client: '' };
}
setMichael = () => {
this.setState({ client: 'Michael' });
};
setNora = () => {
this.setState({ client: 'Nora' });
};
render() {
return (
<div>
<button onClick={this.setMichael}>Michael</button>
<button onClick={this.setNora}>Nora</button>
<ProjectsComponent client={this.state.client} />
</div>
);
}
}
// We will implement this component shortly
class ProjectsComponent extends React.Component {
...
}
In our example, the MyComponent is the parent component, and the child is the ProjectsComponent. The parent component stores the client’s details and passes them to the child component. As the client values get updated, the child gets notified and receives new props
Let's implement the ProjectsComponent showing a list of projects for a selected user:
class ProjectsComponent extends React.Component {
constructor(props) {
super(props);
this.state = { projects: [] };
}
// Emulate server data fetch. Return data after 300 ms timeout
fetchData = client => {
setTimeout(() => {
this.setState({
projects:
client === 'Michael'
? ['Project Aiden', 'Project Brook']
: ['Project Cecilia', 'Project Delta']
});
}, 300);
};
componentDidUpdate(prevProps, prevState) {
// check whether client has changed
if (prevProps.client !== this.props.client) {
this.fetchData(this.props.client);
}
}
render() {
// render a list of projects
return (
<div>
<b>Projects for {this.props.client}</b>
<ul>
{this.state.projects.map(project => (
<li>{project}</li>
))}
</ul>
</div>
);
}
}
By comparing the prevProps and this.props values, we verify the client’s present status. Whenever the client details get updated, we request a list of their projects from a server. On successful receiving the remote data, the component’s state gets updated with a list of projects.
While we update the component's internal state, it triggers a new update and the componentDidUpdate gets called. Extra attention must be given when using the setState function in the componentDidUpdate because if the values are not set correctly, the code block may run an infinite loop. Verify the name of the client in props to prevent infinite loop:
class ProjectsComponent extends React.Component {
constructor(props) {
super(props);
this.state = { projects: [] };
}
// Emulate server data fetch. Return data after 300 ms timeout
fetchData = client => {
setTimeout(() => {
this.setState({
projects:
client === 'Michael'
? ['Project Aiden', 'Project Brook']
: ['Project Cecilia', 'Project Delta']
});
}, 300);
};
componentDidUpdate(prevProps, prevState) {
// check whether client has changed
if (prevProps.client !== this.props.client) {
this.fetchData(this.props.client);
}
}
render() {
// render a list of projects
return (
<div>
<b>Projects for {this.props.client}</b>
<ul>
{this.state.projects.map(project => (
<li>{project}</li>
))}
</ul>
</div>
);
}
}
Another important area where componentDidUpdate is used is to reduce updates. In React, you can leverage the shouldComponentUpdate function to optimize the component performance. This function gets called before an update resulting in a boost and high performance.
React takes the result of shouldComponentUpdate into consideration and updates accordingly. By default, the shouldComponentUpdate function returns true to verify an update. However, you can also override this function and return false if there is no need for updates.
The shouldComponentUpdate function takes the values of the next properties and next state as arguments. This.props and this.state can be used to access current properties and state. However, the function didComponentUpdate is not called if React skips an update:
class MyComponent extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// add condition to check whether need to update
// return false to hint React to avoid update
if (this.props.name !== nextProps.name) {
return false;
}
return true;
}
render() {
return <div></div>;
}
}
React.PureComponent is mainly used for performance optimization. As React component render() function returns the same result with the identical properties and state, you can use React.PureComponent to improve performance in many cases. Pure components are exactly like regular components except for two things: they implement shouldComponentUpdate() with a shallow comparison of props and state, and they don't support the componentDidUpdate() lifecycle hook.
Instead of implementing the shouldComponentUpdate function, use React.PureComponent as a base class for the component. React.PureComponent implements shouldComponentUpdate and subtly compares props and state to check if there is a need for an update. When comparing, it takes the props and state objects properties and confirms the equality of the current and the next values.
class MyComponent extends React.PureComponent {
// we don't need to implement shouldComponentUpdate
// React.PureComponent does that
render() {
return <div></div>;
}
}
The advantage of using React.PureComponent is that you don't have to worry about accidentally rerendering your component when there's no need to. If you forget to add a shouldComponentUpdate() method to a regular component or write one that always returns true with React.PureComponent, the default behaviour is already optimised for performance.
Warning Bells!
There are a few trade-offs to be aware of when using React.PureComponent, though.
First, because the shouldComponentUpdate() method only makes a shallow comparison of props and state, it won't work well if your component has complex data structures. If you need shouldComponentUpdate() to make a deep comparison, you can write it yourself or use a library like Immutable.js.
Secondly, Pure components don't support the componentDidUpdate() lifecycle hook. If you need to do any post-processing after a component update, you'll have to do it in the component's update() lifecycle hook instead.
Let’s look at the componentDidUpdate examples and how we can use them in our project.
Example:1 We will build a basic React application that changes the heading text when the component gets updated.
Step-1: Create a project and call it demoproject:
npx create-react-app demoproject
Step-2: Move to the current directory using the cd command:
cd functiondemo
Step-3: Add the following block of code to your JavaScript file:
mport React from 'react';
class App extends React.Component {
// Define the state
state = {
company: 'KnowHut'
};
componentDidMount() {
// Change the state after 600ms
setTimeout(() => {
this.setState({ company: 'KnowledgeHut' });
}, 600);
}
componentDidUpdate() {
document.getElementById('warning').innerHTML =
'P.s: KnowHut is also known as ' + this.state.company;
}
render() {
return (
<div>
<h1 style={{
margin: 'auto',
width: '50%',
padding: 20,
marginTop: '10%',
border: 'solid 1px black',
textAlign: 'center',
fontSize: 18,
}}>
Best Online Training and Certifications :
{this.state.company}
<div id="warning"></div>
</h1>
</div>
);
}
}
export default App;
Step-4: RUN the code:
npm start
As output, you will see the application changing the text in the heading every time the component gets updated.
Example:2 Using componentDidUpdate() to increment a counter when the component becomes visible.
class ExampleComponent extends React.Component {
constructor(props)
{
super(props);
this.state = {
counter: 0,
};
this.incrementCounter = this.incrementCounter.bind(this);
}
componentDidUpdate(prevProps, prevState) {
if (this.props.isVisible && !prevProps.isVisible) {
this.incrementCounter();
}
}
incrementCounter() {
this.setState((state) => ({ counter: state.counter + 1 }));
}
render() {
return (
<div>{this.state.counter}</div>
);
}
}
In the above example, the component update method sets the state based on props changes. The component's update method is invoked whenever the component's props or state changes. In this case, we are using it to increment a counter when the component becomes visible.
Looking to enhance your coding skills? Join our Python Placement Course and unlock endless opportunities. Python, the versatile programming language, is in high demand across industries. Don't miss out on this chance to boost your career!
ComponentDidUpdate is part of the React component lifecycle. We use it to respond to external changes to a component's details or changes to its internal state. With componentDidUpdate, you can modify the central DOM node, request remote data, and update the internal state of your components. However, this must not be an end to expanding your knowledge in React.
Enhance your expertise with our comprehensive Software Engineering courses, designed to equip you with practical skills and knowledge to excel in the ever-evolving tech landscape.
Unlock your potential with our free Software Development courses, designed to equip you with the skills and knowledge needed to excel in the tech world. Start learning today and advance your career!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources