3 ms·
I use it to handle changes in props. For example load something from network, which goes into redux, redux triggers a props update, so then I do something beca
by hoodoof 9y ago
I use it to handle changes in props.
For example load something from network, which goes into redux, redux triggers a props update, so then I do something because for example now redux state has changed to say "loaded === true"
Is this not the correct function to handle changes in props?
- spicyj 9y agoWhen you see that the props have changed, what do you do? (You said you do "something".) If you are updating the state of that component, that's exactly what the new getDerivedStateFromProps is designed for. If you are doing something else (esp. fetching other data or some other side effect), componentDidUpdate is likely the best place (it receives prevProps as an argument, so you can compare old and new).
- danabramov 9y agoI'd also add that in general we suggest there to be one source of truth for any data. For any particular data, you could put it in Redux -or- in local state, but there is rarely a need to keep it in both. Manually copying things from Redux into local state from `componentWillReceiveProps` (or even with new `getDerivedStateFromProps`) seems unnecessary to me. There are exceptions like rare cases where you want to have a “draft” of some state that can later be “reverted”. But in general you wouldn't want to “sync” state from one source to another.
- hoodoof 9y ago>> When you see that the props have changed, what do you do? "What do I do in componentWillReceiveProps?" It's a good question. Looking through the code I see alot of cases in which I am mapping new props to state, sometimes transforming received network data that is stored in redux, sometimes making a barrier to redirect to a different page if for example some condition has changed. Perhaps these things are relics from before I really came to understand Redux - maybe in most cases I can just directly use props rather than having an intermediate setting of state.
- danabramov 9y ago>sometimes making a barrier to redirect to a different page if for example some condition has changed. That's a side effect. Move that to `componentDidUpdate`: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#side-effects-on-props-change https://reactjs.org/blog/2018/03/27/update-on-async-renderin... >mapping new props to state As I noted in https://news.ycombinator.com/item?id=16711813 https://news.ycombinator.com/item?id=16711813, usually it's not necessary (and complicated your code for nor benefit). For rare cases when it's useful, migrate to `getDerivedStateFromProps`: 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...