Whilst learning Redux
I've came across Reducers
. The documentation states:
The reducer is a pure function that takes the previous state and an action, and returns the next state. (previousState, action) => newState. It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue) .
MDN describes the reduce
method as:
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
I'm still confused on why the Redux definition of a reducer as it's making no sense. Secondly the MDN description doesn't seem correct either. The reduce
method isn't always used to reduce to a single value. It can be used in place of map
and filter
and is actually faster when used in place of chaining.
Is the MDN description incorrect?
Jumping back to the Redux definition of a reducer, it states:
It's called a reducer because it's the type of function you would pass to Array.prototype.reduce(reducer, ?initialValue)
I'm under the impression that a reducer in Redux is responsible for modifying state. An example reducer:
const count = function(state, action) {
if(action.type == 'INCREMENT') {
return state + 1;
} else if(action.type == 'DECREMENT') {
return state - 1;
} else {
return state;
}
}
... I don't see how this is a function that would be passed to reduce
. How is that data being reduced to a single value? If this is a function you would pass to reduce
then state
would be the callback and action
would be the initial value.
Thanks for any clear explanations. It's difficult to conceptualize.
reducer
does not return a single value? Remember that an Array is still a single value. Certainlyreduce
can be used in place ofmap
/filter
, but it's different in that you're working off of one value (the accumulator) instead of operating on each element in isolation.