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

getDerivedStateFromProps: Syncing State to Props

A static method for rare cases where state must derive from props, and why it's usually an antipattern.

getDerivedStateFromProps: Syncing State to Props

What you'll learn: You'll discover React's static method for deriving state from props—and why you should almost never use it.

What It Is

getDerivedStateFromProps is a static lifecycle method that runs before every render (both mount and updates). It allows a class component to update its state based on incoming props. Unlike other lifecycle methods, it's static—it doesn't have access to this.

The Syntax

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Return an object to update state, or null for no update
    if (nextProps.someProp !== prevState.cachedProp) {
      return {
        cachedProp: nextProps.someProp,
        derivedValue: nextProps.someProp * 2
      };
    }
    return null;
  }
}

Why It's Usually Wrong

Think of it like constantly recalculating your grocery list based on what's in your fridge. Most of the time, you should either:

  • Just use the prop directly (no state needed)
  • Use componentDidUpdate to respond to prop changes with side effects
  • Lift the state up so the parent controls it

This method is tempting when you want to "sync" state with props, but that usually means your component's state ownership is confused. If state derives from props, why isn't the parent managing it?

The Rare Valid Use Case

The only legitimate scenario: you need to compare the previous and next props to decide whether to reset some internal state (like a form control that resets when an ID prop changes).

Key Takeaway: getDerivedStateFromProps is a static method that updates state from props before each render, but it's almost always an antipattern—if you're reaching for it, reconsider your component's state design first.