Why are Redux's state functions called reducers?
Solution 1:
The fact that they return a default value (or they have a default argument value) doesn't make them reducers IMHO.
Reducers do not just return default values. They always return the accumulation of the state (based on all previous and current actions).
Therefore, they act as a reducer of state. Each time a redux reducer is called, the state is passed in with the action (state, action)
. This state is then reduced (or accumulated) based on the action, and then the next state is returned. This is one cycle of the classic fold
or reduce
function.
As @azium summed up with state -> action -> state
.
Solution 2:
If you consider the series of actions in your app to be like a list, or maybe more like a stream, it might make more sense.
Take this contrived example:
['apple', 'banana', 'cherry'].reduce((acc, item) => acc + item.length, 0)
The first argument is a function of the form (Int, String) => Int
. Along with an initial value, you pass reduce
what might be called a "reducer function", and you get the result of processing the series of items. So you might say, the reducer function describes what is done with each successive individual item to change the result. In other words, the reducer function takes the previously output and the next value, and it calculates the next output.
This is analogous to what a Redux reducer does: it takes the previous state and the current action, and it calculate the next state.
In true functional programming style, you can conceptually erase the meaning applied to the arguments and the result, and just focus on the "shape" of the inputs and output.
In practice, Redux reducers are typically orthogonal, in the sense that for a given action, they don't all make changes to the same properties, which makes it easy to split their responsibilities and aggregate the output with combineReducers
.
Solution 3:
As already mentioned the name is related to the concept of a reducer in functional programming. You may also find the Merriam-Webster dictionary definition of reducer helpful:
1a. to draw together or cause to converge : consolidate (reduce all the questions to one)
The reducer consolidates actions into a single object representing application state.