React JS Tutorial: Understanding `componentDidUpdate` 🎯

beginner
24 min

React JS Tutorial: Understanding componentDidUpdate 🎯

Welcome back! Today, we're diving into the exciting world of React JS by exploring the componentDidUpdate lifecycle method. This powerful tool allows you to react (pun intended!) to changes in your component's props and state. Let's get started!

What is componentDidUpdate? 📝

componentDidUpdate is a lifecycle method in React that gets called immediately after an update to the component has been performed. This means it's fired whenever a component's state or props change.

Why do we need componentDidUpdate? 💡

Imagine you have a component that fetches data from an API when it mounts and updates its state accordingly. However, you'd like to refetch the data when certain props or state change. componentDidUpdate is perfect for this situation!

When does componentDidUpdate get called? 📝

  • componentDidUpdate gets called whenever the component's state or props change, and not only when the component mounts (unlike componentDidMount).
  • It gets called after the render method is executed, so you can access the updated DOM in your component.

Syntax and Parameters 📝

Here's the syntax for the componentDidUpdate method:

jsx
componentDidUpdate(prevProps, prevState, snapshot) { // Your code here }
  • prevProps: An object that contains the previous props of the component.
  • prevState: An object that contains the previous state of the component.
  • snapshot: A PerfMarker object, only available in React 18+. This object provides performance measurements during the update.

Practical Example 📝

Let's build a simple component that fetches data from an API and updates its state. We'll then use componentDidUpdate to refetch the data when the component's props change.

jsx
import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => this.setState({ data })); } componentDidUpdate(prevProps) { if (prevProps.refresh !== this.props.refresh) { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => this.setState({ data })); } } render() { return ( <div> {this.state.data.map(item => ( <div key={item.id}>{item.name}</div> ))} </div> ); } } export default MyComponent;

In this example, we fetch data when the component mounts and update it using componentDidUpdate when the refresh prop changes.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the `componentDidUpdate` method get called after in the component lifecycle?

That's it for today! You now have a solid understanding of the componentDidUpdate lifecycle method in React JS. In the next lesson, we'll explore the shouldComponentUpdate method and learn how to optimize our components' performance. Until then, happy coding! 🎉