React Redux reducer without action?


(Matt Saunders) #1

For Redux users here I’ve a question about handling reducers if an action is not required…

I’ve not used Redux in a real project yet as I’m just experimenting with it. It looks like this:

  • I have a (custom) dropdown box which says “Select client”
  • Inside the list of options is a list of clients
  • On change, the “Select client” text changes to the selected client name
  1. My list of clients are in a reducer with no action and I’m using mapStateToProps in order to get them for the dropdown
  2. My “Select client” is another reducer which stores the selected client, and has an action to change this based on user selection.

So my questions:

  1. Is it okay to have a reducer without an action? These would typically come from an API fetch request. Is there a case for this list to be fetched outside of Redux? Admittedly in a larger app I would probably also want to perform actions on the client, but in this case, what would be best practice?
  2. Is separating things out to such a granular level the right thing to do? In this case the selected client text is just one tiny UI element that changes based on one action.

Thanks!


(Troy Rhinehart) #2

You’ve mentioned several actions:

  • Action to fetch items
  • Action to handle fetched items
  • Action to handle onChange of select for items

(rob2d) #3

Yep. Reducer’s jobs are purely to mutate things. You may be picking the wrong tool for the job if you’d like to mutate your state without a messenger (e.g. action) to send that message.


(Nick Roberts) #4

I think the answer is that all Redux state must have a reducer to set it. For example, if you get a list of clients from an API, you will need a reducer to set it. The only exception is initial state, and I recommend you make that as empty as possible. All API fetching must happen outside of reducers. Then dispatch an action to make a reducer update Redux. Don’t make actions and reducers too granular. In general, lump everything into one action module and one corresponding reducer module, and break them up only when there is a clear need. However, you do have one action for each conceptual change. HTH