getDerivedStateFromProps method

  1. @override
Map? getDerivedStateFromProps(
  1. Map nextProps,
  2. Map prevState
)
override

ReactJS lifecycle method that is invoked before rendering when new props (nextProps) are received.

It should return a new Map that will be merged into the existing component state, or null to do nothing.

Important Caveats:

  • Unlike componentWillReceiveProps, this method is called before first mount, and re-renders.

  • prevState will be null when this lifecycle method is called before first mount. If you need to make use of prevState, be sure to make your logic null-aware to avoid runtime exceptions.

  • This method is effectively static (since it is static in the JS layer), so using instance members like props, state or ref will not work.

    This is different than the componentWillReceiveProps method that it effectively replaces.

    If your logic requires access to instance members - consider using getSnapshotBeforeUpdate instead.

Example:

@override
getDerivedStateFromProps(Map nextProps, Map prevState) {
  if (prevState['someMirroredValue'] != nextProps['someValue']) {
    return {
      someMirroredValue: nextProps.someValue
    };
  }
  return null;
}

Deriving state from props should be used with caution since it can lead to more verbose implementations that are less approachable by others.

Consider recommended alternative solutions first!

See: reactjs.org/docs/react-component.html#static-getderivedstatefromprops

Implementation

@override
getDerivedStateFromProps(Map nextProps, Map prevState) {
  final tNextProps = typedPropsFactory(nextProps);
  final tPrevState = typedStateFactory(prevState);
  if (tNextProps.isShown! && _isOrWillBeHidden(tPrevState.$transitionPhase)) {
    return _stateToBeginShowing(tNextProps, tPrevState.$transitionPhase);
  } else if (!tNextProps.isShown! && _isOrWillBeShown(tPrevState.$transitionPhase)) {
    return _stateToBeginHiding(tNextProps, tPrevState.$transitionPhase);
  }

  return null;
}