0

In the official Redux docs, it says:

"Reducer" functions get their name because they're similar to the kind of callback function you pass to the Array.reduce() method.

While Array.reduce can reduce 3 or 1000 numbers into 1, therefore "reducing" it to a simple number:

// reducing it to a single sum:
console.log([1, 3, 5, 7, 9].reduce((a, b) => a + b));

How does a Redux reducer actually "reduce" things?

kla
  • 63
  • 1
  • 8
  • I guess `(a, b) => a + b)` is a "reducer", that's ok... so Redux see the user clicking on ordering 2 hamburgers, 1 soft drink, and then check out, all these actions lumping together to "reach a final state" and is done by reducing and reducing? It seems a bit silly... like we play a game of chess, or we go to school, take a shower, and sleep, and it is also reducing? It simply is a series of actions but I don't see anything reducing here. Perhaps if we say our life reduces to death, then we can call it reduce – kla May 14 '21 at 06:18

1 Answers1

0

Redux reducers reduce the an array of all actions into a state.

const finalState = [
    { type: 'INIT'}, 
    { type: 'SOME_ACTION' }, 
    { type: 'SOME_OTHER_ACTION'} 
  ].reduce(reducer, undefined)

or

const nextState = [
    { type: 'SOME_ACTION' }, 
    { type: 'SOME_OTHER_ACTION'} 
  ].reduce(reducer, lastState)
phry
  • 35,762
  • 5
  • 67
  • 81
  • if I see the cart containing one hamburger, and then 2 hamburgers, and then plus a soft drink, I see a "complicator". I don't see a "reducer" – kla May 14 '21 at 16:21
  • It is a play on the "reducer" argument to [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). – phry May 14 '21 at 21:01
  • it can be called a stateConverter or stateMorpher but I don't know why it is a called a reducer because it does not reduce state – kla May 15 '21 at 21:38