I'm wondering if it is bad practice to have 'fat' gDSFP functions. Currently, I have a component that takes in some data and does a bunch of data manipulation
function getDrivedStateFromProps(nextProps, prevState) {
// start doing data manipulation
and along the way if it encounters an error condition it returns a new error slice of state
const someValue = nextProps.something * myFunc()
if (someValue === badThing()) {
return {error: true};
}
// continue doing data manipulation
This repeats several times before it finishes all data manipulation and returns the derivedState that my component needs. I'm curious on what the communities views are on a 'fat' gDSFP functions. My component only runs gDSFPs when the external data source has changed and it needs to derive new state so I don't see where else this logic could live.
I think you may actually be in a situation where using
getDerivedStateFromProps
might not be the best approach at all. In your question you state...Given this statement, it sounds like you can use memoization. Here is this concept discussed on the react docs.
The basic idea is that managing
getDerivedStateFromProps
can get hairy especially when you have lots of logic going on there. If the reason why you want to capture your props in state is only to get a performance boost, then memoization might be your friend.The idea here is that you do not want some logic to run every time your props change, so what this will buy you is that if you have a function whose arguments are the same as they were before, as an example state has not changed, your function will return the last computed result which it had stored in the cache. This library handles this beautifully and is pretty easy to use.
Another concern people often have which may prompt them to reach for
getDerivedStateFromProps
is to ensure that their component does not render unless if the props have in fact changed, so by having the component render based off of computed state this can be achieved.But this too can be achieved without using
getDerivedStateFromProps
. Using PureComponent can give you this same result with much less fuss. Another option can be shouldComponentUpdate.In short, unless you have some very specific reason that
getDerivedStateFromProps
is right for your use case, you may be better off reaching for a solution that involves less hair pulling.