getDerivedStateFromProps does not look like the right tool for what you are trying to do. Instead use componentDidUpdate:

componentDidUpdate(prevProps) {
  const { date } = this.props;
  if (prevProps.date !== date) {
    this.getList(date);
  }
}

It's pretty rare to use getDerivedStateFromProps. For more information on when to use getDerivedStateFromProps I recommend this article

Answer from Nicholas Tower on Stack Overflow
🌐
React
legacy.reactjs.org › docs › react-component.html
React.Component – React
If you’d like, you can reuse some code between getDerivedStateFromProps() and the other class methods by extracting pure functions of the component props and state outside the class definition. Note that this method is fired on every render, regardless of the cause. This is in contrast to UNSAFE_componentWillReceiveProps, which only fires when the parent causes a re-render and not as a result of a local setState. getSnapshotBeforeUpdate(prevProps, prevState) getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g.
Discussions

how to use getDerivedStateFromProps instead of componentWillReceiveProps in React
I like to update my code to use getDerivedStateFromProps instead of componentWillReceiveProps as the I am receiving deprecated error. The component is receiving a date prop and every time the date is More on stackoverflow.com
🌐 stackoverflow.com
How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps
It looks like componentWillReceiveProps is going to be completely phased out in coming releases, in favor of a new lifecycle method getDerivedStateFromProps:static getDerivedStateFromProps(). Upon More on stackoverflow.com
🌐 stackoverflow.com
reactjs - react js getDerivedStateFromProps is calling continuously - Stack Overflow
I have a problem where getDerivedStateFromProps() is calling continuously because state is updating in toggle(). I need to call the toggle() when the props got updated · Help me out to resolve the problem. ... You can use componentDidUpdate for this. ... componentDidUpdate will be called with prevProps ... More on stackoverflow.com
🌐 stackoverflow.com
getDerivedStateFromProps - responding to change in props
However, having read through #12188, ... against prevProps to respond to a change) is by copying props into state - which appears to directly contradict your article on derived state anti patterns. To say the least I'm a bit confused - should the documentation be changed (and getDerivedStateFromProps should not ... More on github.com
🌐 github.com
7
August 29, 2018
🌐
DhiWise
dhiwise.com › post › best-practices-for-using-getderivedstatefromprops-in-your-react-applications
The Role of getDerivedStateFromProps in the React
October 27, 2023 - The getDerivedStateFromProps method takes two parameters: nextProps and prevState. nextProps is an object representing the new props that the component is receiving, and prevState is an object representing the current state of the component.
🌐
React
react.dev › reference › react › Component
Component – React
getSnapshotBeforeUpdate(prevProps, prevState) render() setState(nextState, callback?) shouldComponentUpdate(nextProps, nextState, nextContext) UNSAFE_componentWillMount() UNSAFE_componentWillReceiveProps(nextProps, nextContext) UNSAFE_componentWillUpdate(nextProps, nextState) static contextType · static defaultProps · static getDerivedStateFromError(error) static getDerivedStateFromProps(props, state) Usage ·
Top answer
1 of 4
119

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

2 of 4
63

As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.

If you just want to compute some derived data, either:

  1. Do it right inside render
  2. Or, if re-calculating it is expensive, use a memoization helper like memoize-one.

Here's the simplest "after" example:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...
  }
}

Check out this section of the blog post to learn more.

🌐
Medium
medium.com › @rajeevranjan2k11 › making-sense-of-getderivedstatefromprops-a-useful-manual-for-a-react-developer-65408a689d28
Making Sense of getDerivedStateFromProps: A Useful Manual for a React Developer
September 26, 2024 - class UserProfile extends React.Component { constructor(props) { super(props); this.state = { userData: {}, isLoading: true, }; } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.userId !== prevState.prevUserId) { // Reset state if userId has changed return { userData: {}, isLoading: true, prevUserId: nextProps.userId }; } return null; } componentDidMount() { this.fetchUserData(this.props.userId); } componentDidUpdate(prevProps) { if (prevProps.userId !== this.props.userId) { this.fetchUserData(this.props.userId); } } fetchUserData(userId) { // API call to fetch user data based on userId // Once data is fetched, update state // this.setState({ userData: fetchedData, isLoading: false }); } render() { const { userData, isLoading } = this.state; return isLoading ?
Find elsewhere
🌐
Larry-price
larry-price.com › blog › 2018 › 06 › 27 › how-to-use-getderivedstatefromprops-in-react-16-dot-3-plus
How to Use getDerivedStateFromProps in React 16.3+ - Larry Price
As opposed to getDerivedStateFromProps, we have access to the context provided by this. Note that this method also has arguments for prevProps and prevState, which provides the previous versions of the component’s props and state for comparison to the current values.
🌐
GitHub
github.com › tlareg › react-prev-props
GitHub - tlareg/react-prev-props: Little utility to read previous props in getDerivedStateFromProps. It helps to fast replace depricated componentWillReceiveProps.
import { prevProps } from 'react-prev-props'; // ... static getDerivedStateFromProps(nextProps, prevState) { const { nextState, changedProps } = prevProps( ['value', 'value2', 'value3'], { nextProps, prevState } ); if (changedProps) { // props changed, we can insert some additional logic return { ...nextState, // we can reset state props with changed props ...changedProps, } } return nextState; }
Author   tlareg
🌐
DigitalOcean
digitalocean.com › community › tutorials › react-get-derived-state
Using Derived State in React | DigitalOcean
July 1, 2018 - class List extends React.Component ... } // Return null if the state hasn't changed return null; } componentDidUpdate(prevProps, prevState) { if (this.props.selected !== prevProps.selected) { this.selectNew(); } } // ......
🌐
Jasonkang14
jasonkang14.github.io › posts › react › react-life-cycle-get-derived-state-from-props-with-mobx
React Lifecycle - Using getDerivedStateFromProps with React Native and MobX - Blog by Jason Kang
static getDerivedStateFromProps(props, state) { if (toJS(props.MainScreenStore.snsPostArr[0]).length !== state.prPostArr.length) { return { prPostArr: toJS(props.MainScreenStore.snsPostArr[0]), likedPostSet: new Set(toJS(props.MainScreenStore.snsPostArr[1])) } } return null; }
🌐
GitHub
github.com › reactjs › rfcs › issues › 19
Static Lifecycle Methods’ getDerivedStateFromProps access to previous props · Issue #19 · reactjs/rfcs
January 29, 2018 - The example illustrating use of this pattern notes that “if the calculation is fast enough it could just be done in render”, so I’m guessing that the primary motivation for using getDerivedStateFromProps should be more expensive calculations. But I also saw the discussion about the static deriveStateFromProps(props, state, prevProps) { proposal, which suggests that this kind of a check won’t be possible.
🌐
React
legacy.reactjs.org › blog › 2018 › 06 › 07 › you-probably-dont-need-derived-state.html
You Probably Don't Need Derived State – React Blog
June 7, 2018 - // In this simple example, that's just the email. if (props.userID !== state.prevPropsUserID) { return { prevPropsUserID: props.userID, email: props.defaultEmail }; } return null; } // ... } This also provides the flexibility to only reset parts of our component’s internal state if we so choose. (Click here to see a demo of this pattern.) ... Even though the example above shows getDerivedStateFromProps, the same technique can be used with componentWillReceiveProps.
🌐
Medium
medium.com › @farihatulmaria › what-is-getderivedstatefromprops-props-state-as-a-lifecycle-in-reactjs-a06594262ea4
What is getDerivedStateFromProps( props,state) as a lifecycle in ReactJs? | by Farihatul Maria | Medium
October 5, 2024 - The purpose of getDerivedStateFromProps() is to allow developers to update the component's state based on changes in the props. This is particularly useful in situations where the state of a component is dependent on the props.
🌐
GitHub
github.com › facebook › react › issues › 13008
Exposing prevProps in getDerivedStateFromProps for persistent view animations · Issue #13008 · facebook/react
June 9, 2018 - Do you want to request a feature or report a bug? Request a feature What is the current behavior? getDerivedStateFromProps does not expose prevProps What is the expected behavior? getDerivedStateFromProps should expose prevProps for clea...
🌐
GitHub
github.com › facebook › react › issues › 13505
getDerivedStateFromProps - responding to change in props · Issue #13505 · facebook/react
August 29, 2018 - The documentation states This method exists for rare use cases where the state depends on changes in props over time However, having read through #12188, it appears the only way to achieve this (checking props against prevProps to respon...
Author   Billy-
Top answer
1 of 3
7

getDerivedStateFromProps is not a direct alternative to componentWillReceiveProps, purely because of the fact that its called after every update, whether its the change in state or change in props or re-render of parent.

However whatever is the case, simply returning the state from getDerivedStateFromProps is not the right way, you need to compare the state and props before returning the value. Else with every update the state is getting reset to props and the cycle continues

As per the docs

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a <Transition> component that compares its previous and next children to decide which of them to animate in and out.

Deriving state leads to verbose code and makes your components difficult to think about. Make sure you’re familiar with simpler alternatives:

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

If you want to re-compute some data only when a prop changes, use a memoization helper instead.

If you want to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

P.S. Note that the arguments to getDerivedStateFromProps are props and state and not nextProps and prevProps

To get into more details,

In order to make changes based on props change, we need to store prevPropsState in state, in order to detect changes. A typical implementation would look like

static getDerivedStateFromProps(props, state) {
    // Note we need to store prevPropsState to detect changes.
    if (
      props.myPropsState !== state.prevPropsState
    ) {
      return {
        prevPropsState: state.myState,
        myState: props.myPropsState
      };
    }
    return null;
  }
2 of 3
1

Finally, I resolved my issue. It was a painful debugging:

// Child Component

// instead of this
// this.props.onMyDisptach([...myPropsState])

// dispatching true value since myPropsState contains only numbers
this.props.onMyDispatch([...myPropsState, true])

This is because, I have two conditions: 1) on checkbox change (component) 2) on reset button pressed (child component)

I was needing to reset the states when reset button is pressed. So, while dispatching state to the props for reset button, I used a boolean value to know it's a change from the reset. You may use anything you like but need to track that.

Now, here in the component, I found some hints to the differences between componentWillReceiveProps and getDerivedStateFromProps after debugging the console output.

// Component
static getDerivedStateFromProps(props, state) {
    const { myPropsState: myState } = props
    // if reset button is pressed
    const true_myState = myState.some(id=>id===true)
    // need to remove true value in the store
    const filtered_myState = myState.filter(id=>id!==true)
    if(true_myState) {
      // we need to dispatch the changes to apply on its child component
      // before we return the correct state
      props.onMyDispatch([...filtered_myState])
      return {
        myState: filtered_myState
      }
    }
    // obviously, we need to return null if no condition matches
    return null
  }

Here's what I found the results of the console output:

  • getDerivedStateFromProps logs immediately whenever props changes

  • componentWillReceiveProps logs only after child propagates props changes

  • getDerivedStateFromProps doesn't respond to the props changes ( I meant for the dispatch changes as in the example code)

  • componentWillReceiveProps responds to the props changes

  • Thus, we needed to supply the changes to child component while using getDerivedStateFromProps.

The process of pasting true value in the state I require because getDerivedStateFromProps handle all the changes unlike componentWillReceiveProps handles only the child component dispatches the changes to the props.

By the way, you may use custom property to check if it is changed and update the value if getDerivedStateFromProps but for some reason I have to tweak this technique.

There might be some confusion on my wording but I hope you'll get it.

🌐
HackerNoon
hackernoon.com › replacing-componentwillreceiveprops-with-getderivedstatefromprops-c3956f7ce607
Replacing ‘componentWillReceiveProps’ with ‘getDerivedStateFromProps’ | HackerNoon
May 13, 2018 - programming#react#javascript#reactjs#componentwillreceiveprops#getderivedstatefromprops · Arweave · ViewBlock · Terminal · Lite · Coderoad · Devfaq · Thinbug · Errorsbase · Openweaver · Shijianchuo · Hashnode · Digraph · Learnrepo · Openweaver ·