Redux FAQ: Reducers

    Reducers

    Many users later want to try to share data between two reducers, but find that combineReducers does not allow them to do so. There are several approaches that can be used:

    • If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
    • You may need to write some custom functions for handling some of these actions. This may require replacing with your own top-level reducer function. You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
    • such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.
      In general, remember that reducers are just functions—you can organize them and subdivide them any way you want, and you are encouraged to break them down into smaller, reusable functions (“reducer composition”). While you do so, you may pass a custom third argument from a parent reducer if a child reducer needs additional data to calculate its next state. You just need to make sure that together they follow the basic rules of reducers: , and update state immutably rather than mutating it directly.

    Further information

    Documentation

    Do I have to use the switch statement to handle actions?

    No. You are welcome to use any approach you'd like to respond to an action in a reducer. The switch statement is the most common approach, but it's fine to use if statements, a lookup table of functions, or to create a function that abstracts this away. In fact, while Redux does require that action objects contain a field, your reducer logic doesn't even have to rely on that to handle the action. That said, the standard approach is definitely using a switch statement or a lookup table based on type.

    Further information