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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store