assiegee
assiegee

Reputation: 351

how to use getDerivedStatefromProps in my component

The component receives a list of Objects as prop. I want to display it with infinite scroll. It has the state "curNum", which is current number of items to be displayed. "curNum" changes when scroll down so the list of items is sliced based on the "curNum".

The list of object will be updated by the parent component, and "curNum" should be reset to initial value.

With componentWillReceiveProps I can do:

componentWillReceiveProps(newProps) {
  this.setState({
  curNum: initNum,
 });
}

but how can I rewrite it using getDerivedStateFromProps? I read that the new method will be triggerged even if the state changes. So how can I know I am recieving new props?

Do I have to mirror a copy of the list to the sate and then deep check if the list of objects are equal every time?

Upvotes: 2

Views: 1377

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281656

There are a few ways that you can use to update the state when props change

  1. Use getDerivedStateFromProps: Note that its suggested that you avoid using this method as much as possible since this is called on each update and initial render and not just on Parent component re-render or props change. If however you want to use it, you need to store the prevState too

Code:

static getDerivedStateFromProps(props, state) {

  if (state.prevCurNum !== props.initNum) {
     return {
         currNum: props.initNum,
         prevCurNum: props.initNum
     }
  } else {
      return { prevCurNum: props.initNum }
  }
}
  1. Assign the state from props in constructor and control the key props to component

code

<MyComponent key={this.state.initNum} initNum={this.state.initNum} />

and in MyComponent

constructor(props) {
    super(props);
    this.state= {
       currNum: props.initNum
    }
}

In the above example if the prop initNum changes, the key to the component will change and it will result in the component to re-mount calling its constructor

  1. The third way is to use memoization in render, but its mostly useful when the state is derived from a complex computation of props and isn't supposed to change locally.

Upvotes: 1

Related Questions