r/reactjs • u/dance2die • Nov 28 '19
Why you should choose useState instead of useReducer - Free Code Camp
https://medium.com/free-code-camp/why-you-should-choose-usestate-instead-of-usereducer-ffc80057f815
40
Upvotes
4
u/dance2die Nov 28 '19 edited Nov 28 '19
Fascinating approach on why to use
useStateoveruseReducer.The author lists reasons to choose
useReducerand howuseStatecan be used to take advantage of reasons thereof.Also mentions the downsides of using
useState.There are some insightful comments, so check'em out too.
10
u/[deleted] Nov 28 '19
I might be missing something here, but what you have done with
useApiis essentially to reimplementuseReducer?It takes a function that gets the previous value and a way to update the value. You’ve essentially spread out the updater logic. And lost the ability to read props in the reducer fn.
10
u/cairnival Nov 28 '19
THIS.
Reducers deal with a dispatch function, which take one of several action types A, B, C, and produces a result R. The number of inhabitants of this type is RA + B + C.
Contrast that with an object with each action as its own function. The number of inhabitants of this type is RA * RB * RC.
Notice that it they are algebraically equivalent. They model the exact same thing in slightly different ways. But an object full of nicely named functions you can call is IMO a far more natural way to model most things.
5
u/darrenturn90 Nov 28 '19
I think he means why he prefers a keyed reducer over a switch based reducer - but honestly it’s much of a muchness and being able to serialise dispatch actions has its own advantages
6
u/Skeith_yip Nov 28 '19
Love it or hate it. End of the day...
useStatestill usesuseReducer. Oops.