Course contentsShow
← React
Lesson 298 of 2,3969. Class Components (Legacy Overview)Free lesson

componentDidUpdate: Responding to Props or State Changes

Running side effects after updates, with prevProps and prevState for comparison to avoid infinite loops.

componentDidUpdate: Responding to Props or State Changes

What you'll learn: How to run side effects after your class component updates, and how to avoid infinite loops by comparing previous values.

The Core Idea

componentDidMount runs once after the first render. But what about side effects you need to run after subsequent renders—when props or state change?

That's where componentDidUpdate comes in. This lifecycle method fires after every render except the initial mount. It receives two arguments that let you compare the old values to the new ones: prevProps and prevState.

Why You Need Comparison

Here's the critical part: if you call this.setState() inside componentDidUpdate without checking conditions, you'll create an infinite loop (update → componentDidUpdate → setState → update → componentDidUpdate → ...).

The pattern is always:

  1. Compare the new value to the previous value
  2. Only trigger side effects if something actually changed

Basic Pattern

class UserProfile extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    // Only fetch new user data if the userId prop changed
    if (this.props.userId !== prevProps.userId) {
      this.fetchUserData(this.props.userId);
    }

    // Only save to localStorage if the theme changed
    if (this.state.theme !== prevState.theme) {
      localStorage.setItem('theme', this.state.theme);
    }
  }
}

Notice the conditional checks before doing anything. Without them, you'd be fetching or saving on every render, regardless of whether it's necessary.

Key Takeaway: componentDidUpdate lets you respond to prop or state changes after a re-render, but you must always compare prevProps or prevState to current values to avoid infinite loops and unnecessary work.