Reducers
Planted 02021-05-27
What are they?
The idea for this started by me not understanding reduce
in JavaScript. It’s used to transform an array, but also there’s functions? And I just don’t know what’s going on. So let’s understand.
-
Need to iterate over an array? – we can use
forEach
,for
orfor..of
. -
Need to iterate and return data for each element? – you use
map
. -
Need to calculate a single value based on the array? – use the
reduce
andreduceRight
methods.
The function is applied to all array elements one after another and “carries on” its result to the next call.
Arguments:
- accumulator – is the result of the previous function call, equals initial the first time (if initial is provided).
- item – is the current array item.
- index – is its position.
- array – is the array.
The first argument stores the combined result of all previous executions. And at the end it becomes the result of reduce
.
Okay, but the React useReducer
hook looks like this:
(Curious about React useState and useReducer? I made a simple example where I refactor multiple useState
functions into a single useReducer
.)
The const [] = …
is interesting… what’s that doing again?
Here’s another example of a reducer