Skip to content
Timo Dörr edited this page May 4, 2018 · 4 revisions

Reducers are functions that take a state, an optional payload, and return a new state. In other words, a reducer creates a new state based on the prevous state and some optional arguments.

In reactive-state, a reducer uses the type Reducer<S, P> with state S and optional payload P, although this is just a type definition if you use TypeScript. You can omit specifying the signature (it will be checked later when adding the reducer to a store):

const incrementReducer: Reducer<number> = state => state + 1;
const addReducer: Reducer<number, number> = (state, increment) => state + increment;

const clearTodosReducer: Reducer<string[]> = state => [];

Reducers must be pure functions (for every input they produce the same output). Additionally, they should perform immutable operations. This includes creating immutable copies of all levels of nesting of any updated properties on the state. See the Redux docs on nested updates fore more details.

If a reducer decides that no changes are necessary, it is ok to return the current state instance (without creating an immutable copy).