Redux - relation of reducers to actions Redux - relation of reducers to actions reactjs reactjs

Redux - relation of reducers to actions


1: how does the store know which reducer to use-> This is based entirely on the action type.

2: Do type names have to be unique?-> This is not a rule. But mostly, yes. Each action has a distinct type name and the corresponding reducer gets invoked.

3: To whom or what does the reducer pass the new state object to, the store or the action?-> The reducer does not pass the new state object anywhere. Basically, it triggers a state change event to all your react components that are listening to it. All components listening to the changed state get re-rendered, with the new version of the state, thereby updating your DOM.


In a typical Redux setup, the actions are dispatched to ALL reducers and it's up to the reducers to decide if they care about that action. A common pattern is a switch in the reducer that checks action.type, has cases for actions it cares about and a default case that just returns the current state like this:

export default (state = false, action) => {  switch (action.type) {    case START_LOADING:      return true;    case STOP_LOADING:      return false;    default:      return state;  }}

In this case, I am telling my reducer it only cares about the actions with type START_LOADING or STOP_LOADING and that in all other cases it should just return it's previous state.

For a good understanding of Redux (and Flux) I'd suggest you check out Code Cartoons by Lin Clark or her video which covers most of the same things.


Generally, you only have one reducer responsible for the complete state.

This reducer can be split up into different smaller reducer functions each responsible for a different slice of the state. For example Redux's combineReducers() utility could do that, but you can also do it by hand.

If you use combineReducers(), each of the reducer functions is executed for each dispatched action. They then decide purely based on the action type whether the action should affect its slice of the state. If so, an updated copy of this slice is returned. If its slice is not affected by the action, it is returned unchanged.