Search:   Dictionary All Posts
Store Your Knowledge at the Brain Bank!

static getDerivedStateFromProps - how to use

Summary - getDerivedStateFromProps is a static method, which means it does not have access to the 'this' keyword, so how then do you update the state?
getDerivedStateFromProps is used to check if props the component use have changed and are different from the previous state that was storing the old props. If they have changed, then you can update the state to use the newProps. Updating the state will cause render to run and thus your component will be up to date.

But because getDerivedStateFromProps is a static method it does not have access to the this keyword. So how can we update state if we can't call this.setState()?

The answer is simple, you just return an object with the new state values.

If nothing has changed you must return NULL. 


static getDerivedStateFromProps = (nextProps, prevState) => {
    if(nextProps.itemName === prevState.itemName) {
        return null

    return {
        itemName: nextProps.itemName

See source from answer in Stack Overflow