The first approach is indeed wrong, because you should use useMemo for derived state, instead of useState+useEffect, the second approach is dangerous since it can lead to slow renders and infinite re-rendering, so if you are doing complex manipulation and/or passing the derived state down to another component you should use the derived state factories and place it inside a useMemo
I suppose "dangerous" only if those calculations are slow? if the time to execute them is negligible then useMemo would probably be overkill ... otherwise then yes, it would be the recommended approach :)
If the calculations are expensive, then yes, useMemo would be ideal, however most derivations are quite trivial in my experience and using a pure function to compute takes less effort and cognitive load to set up. Also, pure functions are inherently easier to test as well. Thanks for the feedback!
You can declare the pure functions exactly the sema way, and test them as well, just wrap them inside the useMemo when calling, for me the golden rule is: if you are experienced, check your render times and render counts to decide using it or not, if you are a beginner and you are not sure always wrap derived state inside useMemo, because the using it when it is not needed will be negligible, but not using it when it is needed will give you so much headaches
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The first approach is indeed wrong, because you should use useMemo for derived state, instead of useState+useEffect, the second approach is dangerous since it can lead to slow renders and infinite re-rendering, so if you are doing complex manipulation and/or passing the derived state down to another component you should use the derived state factories and place it inside a useMemo
I suppose "dangerous" only if those calculations are slow? if the time to execute them is negligible then useMemo would probably be overkill ... otherwise then yes, it would be the recommended approach :)
If the calculations are expensive, then yes, useMemo would be ideal, however most derivations are quite trivial in my experience and using a pure function to compute takes less effort and cognitive load to set up. Also, pure functions are inherently easier to test as well. Thanks for the feedback!
You can declare the pure functions exactly the sema way, and test them as well, just wrap them inside the useMemo when calling, for me the golden rule is: if you are experienced, check your render times and render counts to decide using it or not, if you are a beginner and you are not sure always wrap derived state inside useMemo, because the using it when it is not needed will be negligible, but not using it when it is needed will give you so much headaches