According to the official documentation, getDerivedStateFromProps
method exists for rare use cases where the state depends on changes in props
over time, so we should avoid it as much as we can. However, for some edge cases, sometimes due to the tech stack limitation, in which you have to keep a copy of the props
in the state
, that could become obsolete as the application state
– sometime the redux store state
– changes and then that need to be propagated to the internal state
of an specific component. The following snippet has an example of how that method could be used.
Let’s suppose you have a Thumbnail
image component, and you have two props
, uri
and imageSize
. Here is how normally you have its constructor
:
constructor(props) { super(props); this.state = { imageSize: props.imageSize, uri: props.uri, }; }
Prior to getDerivedStateFromProps
, you normally used componentWillReceiveProps
, and that could be like this:
componentWillReceiveProps(nextProps) { const { uri: nextUri } = nextProps; const { uri } = this.state; if (uri !== nextUri) { this.setState({ uri: nextUri }); } }
Conversely, here is the equivalent getDerivedStateFromProps
:
static getDerivedStateFromProps(nextProps, state) { const { uri: nextUri } = nextProps; const { uri } = state; if (uri !== nextUri) { return { uri: nextUri, }; } return {}; }
Hope that helps!
Happy coding!