Does it matter to return only modified state attributes in getDerivedStateFromProps()?

38 views Asked by At

I know that in React 16 new lifecycle method getDerivedStateFromProps() I should return null if there is nothing to change in state, but I wonder about case when I have to update state anyway, but amount of modified state attributes may vary. Does it matter if I include the superfluous attributes that haven't changed in the returned object?

In other words, is it better to:

static getDerivedStateFromProps(nextProps, prevState){
  const foo = /* .. some calculation from props here */
  const bar = /* .. some calculation from props here */
  if (foo === prevState.foo && bar === prevState.bar) {
    return null;
  }
  return {
    foo,
    bar
  };
}

or I should better limit the amount of attributes in the returned object after verifying they haven't changed anyway:

static getDerivedStateFromProps(nextProps, prevState){
  const foo = /* .. some calculation from props here */
  const bar = /* .. some calculation from props here */
  if (foo === prevState.foo && bar === prevState.bar) {
    return null;
  }
  const newState = {};
  if (foo !== prevState.foo) {
    newState.foo = foo;
  }
  if (bar !== prevState.bar) {
    newState.bar = bar;
  }
  return newState;
}
0

There are 0 answers