3 ms·
From the post it looks like getDerivedStateFromProps does not receive the old props as an argument. I can think of cases where that would be helpful, has this b
by aravindet 9y ago
From the post it looks like getDerivedStateFromProps does not receive the old props as an argument. I can think of cases where that would be helpful, has this been considered?
- danabramov 9y agoYes. Our recommendation is to put such values on the state (like state.prevRow in the blog post example). This frees up React to not hold into the whole previous props object in some cases in future versions. It’s a bit more verbose but it also solves the problem of prevProps being null on first render (and thus forcing you to write an extra check every time you use this method).
- marcins 9y agoI don't think you need it - since you're deriving state from props you can just derive from the new props and compare to the old state. At least I believe that's the reasoning.
- aravindet 9y agoIn my use case, the component receives the URL of a resource as a prop, and it re-fetches the resource from a backend when the URL changes. I'd like to avoid the expensive fetch when it's some other prop that changed. Copying the URL to the state will work, although it's a bit more verbose.
- marcins 9y agoThat's probably something that belongs in `componentDidUpdate`, you'll have access to `prevProps` there to compare whether you need to trigger a new fetch. I don't believe that `getDerivedStateFromProps` should have any side-effects.
- brianvaughn 9y agoThis was implied but not explicitly covered in the blog post. I updated it this morning to be more explicit [1]! > You may notice in the example above that props.currentRow is mirrored in state (as state.lastRow). This enables getDerivedStateFromProps to access the previous props value in the same way as is done in componentWillReceiveProps. > You may wonder why we don’t just pass previous props as a parameter to getDerivedStateFromProps. We considered this option when designing the API, but ultimately decided against it for two reasons: > * A prevProps parameter would be null the first time getDerivedStateFromProps was called (after instantiation), requiring an if-not-null check to be added any time prevProps was accessed. > * Not passing the previous props to this function is a step toward freeing up memory in future versions of React. (If React does not need to pass previous props to lifecycles, then it does not need to keep the previous props object in memory.) 1: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props https://reactjs.org/blog/2018/03/27/update-on-async-renderin...