Reducer function in Javascript

Reducers are important in Redux for state management. It is essentially a function that takes in two arguments, current state and action, and returns a new state based on both arguments.

Looking at this, a reducer is just simple Javascript function.

For example purposes, let’s say we have an array of integers and we want to find out the sum of all the integers in the array.

We can create a custom reducer function to find the sum.

If you compare the both examples of the reducer functions I provided, you can see that they are very similar. In this specific case, the returned value of the reducer function is assigned to the accumulator which the callback’s return values. current is the current element being processed.

The reduce() method is needed for the custom reducer method. In short, .reduce executes the callback function. The variable sum will return the sum of arr which is 6.

In terms of state management, reducers always create a new state dependent on the currentState and action.

In this example, the reducer manages the state depending on the action of ‘INCREASE’ or ‘DECREASE’.

If the action type is ‘INCREASE’ the currentState will increment, ‘DECREASE’ will decrement and if there is no action that matches the type conditions, the currentState will remain the same.

Reducers can be used in conjunction with the reduce() method allowing custom functions to be used on arrays. Mainly, it is important in Redux because it simplifies code by making state maintenance more predictable.

Software Engineer

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