What is the Reducer function in JavaScript?

Reducers are in ReactJS are important because they play a big role in Redux for state management. It is a function that takes two arguments, the current state and action, and then return a new state based on both parameters.

A simple version of the code looks like this:

A more complex version of reducer looks like this:

Example of Case/Switch statements with the reducer

Looking at the code snippet of the simpler version of the reducer, we can see it’s just a simple JavaScript function. A more broken down version of this is this:

For another example, let’s say we have an array of integers and we need to find the sum of all the integers in the array. Well then we can create a custom reducer function to find that sum

Array of Integers

Comparing both examples of the reducer functions provided above, you can see that they are very similar. In this instance, the returned value of the reducer function is assigned to the accumulator which accumulates the callback’s return values. Current is the current element being processed.

Full Stack Software Engineering Student at Flatiron School New York City