Subscribe for updates and more.

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 or for..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 and reduceRight methods.
// Reduce Syntax
let value = arr.reduce(function(accumulator, item, index, array) {
  // ...
}, [initial]);

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.
// Reduce example
let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((sum, current) => sum + current, 0);

alert(result); // 15

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:

// React useReducer hook
const [state, dispatch] = useReducer(reducer, initialArg, initialState);

(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?

// Realizing what the array is doing
const [getter, setter] = "what"

console.log(getter) //w
console.log(setter) //h

Here’s another example of a reducer

function findLongestWord (str) {
  return str.split(' ')
    .reduce((longest, word) =>
      word.length > longest.length
        ? word
        : longest
  , '')
}
findLongestWord('Find the longest word') // longest