Understanding Array.reduce()
Forming the correct mental picture of an important tool
In my experience, a lot of developers write the reduce function with a mental model of its semantics. It is approached as a boilerplate-y function. A reduce function kinda gets booted like this in the code:
data.reduce((acc, item) => {
// do the thing;
// return something
}, initialValue);
All good but what could really help is to split this into two parts:
- The reducer function
- The reduction itself
The reducer is simply a combiner function. It takes two inputs and returns a new value. In the context of a reduction, it takes an existing value (the accumulator) and value from an array to create a new value. For example, an add function:
const add = (a, b) => a + b;
The reduction function iterates over an array, combining each of its items sequentially with an accumulator. The initial value argument provides the input the combiner function at index, 0.
[1, 2, 3].reduce(add, 0)
The reduction function iterates over an array, combining each of its items sequentially with an accumulator. The initial value argument provides the input the combiner function at index, 0.
[1, 2, 3].reduce(add, 0)
Having a mental model of a combiner function and the reduction helps understand what reduce really does. This in turn makes your understanding much clearer on what a Redux styled reducer does.
React’s useReducer() hook
React’s useReducer hook allows you to manage state in a very clean way. You may enjoy these posts:
And this: