DEV Community

Discussion on: Combining Reducers

Collapse
 
markerikson profile image
Mark Erikson • Edited

Nice post! Got a couple tips for you.

First, I see that you've got this line in the reducer:

id : cuidFn()

cuid generates random IDs. Ideally, reducers should never be doing anything that involves randomness, because it means they are no longer "pure". Pure functions should always return the exact same result when given the same inputs. A reducer that produces random numbers or IDs would be returning a different result each time it was called.

Now, in reality, generating random IDs in a reducer is unlikely to meaningfully break anything except in rare cases, like doing time-travel debugging. Still, it's a good practice to avoid randomness in reducers, same as you'd avoid mutating state. If possible, try to put that random number generation where you're creating the action, when you dispatch it. (If you're interested, a while back I wrote a post on experimenting with sorta-kinda generating repeatable random numbers in a reducer.)

Also, as a side note: I don't think you needed to assign const cuidFn = cuid. The default export of the cuid library is just that function - you can do import cuid from "cuid", and then just call it directly like const id = cuid(). I also don't think you need parentheses around (combineReducers) either.

On the topic of combineReducers, we've got a Redux docs page that specifically has some more information on using combineReducers effectively.

Finally, I'd encourage you to check out our new Redux Starter Kit package. It includes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once without writing any action types or action creators by hand:

redux-starter-kit.js.org

Once you're familiar with the core ideas of using Redux, the RSK package can really help you simplify a lot of your code.

Hope that helps. Keep up the good writing, and lemme know if you've got any questions I can help with!

Mark Erikson
Redux maintainer

Collapse
 
kritirai profile image
Kriti Rai

Mark, thank you for such an amazing feedback. It means a lot. The lines including cuid were given by the lab and I did not pay much attention to tweaking them (maybe I can transfer that over to the react component to deal with it) but I will keep your advice in mind while working with reducers. Thanks for the docs and RSK package reco. I will make sure to check them out. Cheers!