Question

Redux uses a state reducer pattern where essentially you create a pure function that looks like:

function reducer (previousState, action) {
    //...
    return newState; 
}

This looks similar to JavaScript's Array.reduce function, so I don't think the concept of a 'reducer' is something original to Redux.

However, when I google terms like 'reducer function' or 'reducer pattern' I only get results that are about Redux. (Although down the list is NgRx documentation about reducers).

Can someone give me definitive reference/answer the explains the concept of reducer functions in functional programming generally?

Was it helpful?

Solution

As mentioned in a comment, the pattern is called a "fold", which many other languages implement as a function called "reduce" -- thus redux's name for it. Wikipedia's page is as usual a firehose of information that is difficult to, ah, reduce to a simple textual explanation. I'll give it a stab:

A fold is most easily seen as a function that takes a value, a list, and a function that will "update" that value for each item in the list. For every item in the list, the function is applied to the current value and the single list item, returning the new value. When the list is empty, the final return value of the fold is the final updated value.

In the case of redux, the value is the state, and the "list" is the conceptual infinite stream of actions that are generated by the program invoking actions (other frameworks like RxJS make this stream more explicit). The reducer takes the state and one action from this stream, and returns the new state.

Licensed under: CC-BY-SA with attribution
scroll top