Skip to main content

Reducer

In Zedux, reducers are exactly the same as in Redux and React. A reducer is just a function that receives the current state and an action and returns the new state.

Stores can be configured with reducers by passing a reducer to createStore() or store.use().

Example

import { createStore } from '@zedux/react'

const counterReducer = (state = 0, action) => {
if (action.type === 'increment') {
return state + 1
}

if (action.type === 'decrement') {
return state - 1
}

return state
}

const store = createStore(counterReducer)

store.getState() // 0
store.dispatch({ type: 'increment' }) // 1
store.dispatch({ type: 'increment' }) // 2
store.dispatch({ type: 'decrement' }) // 1

Creation

While you can create reducers manually like we just did, Zedux exports a high-level createReducer() factory for creating them easily:

import { createReducer, createStore } from '@zedux/react'

const counterReducer = createReducer(0) // the initial state
.reduce('increment', state => state + 1)
.reduce('decrement', state => state - 1)

const store = createStore(counterReducer)

store.getState() // 0
store.dispatch({ type: 'increment' }) // 1
store.dispatch({ type: 'increment' }) // 2
store.dispatch({ type: 'decrement' }) // 1

Definition

type Reducer<State = any> = (state: State | undefined, action: Action) => State
state

The current state of this reducer or undefined if this is the first time the reducer is run. Note that reducers should never return undefined.

Common practice is to assign this parameter to a default value.

action
An Action object. Note that this will never be an ActionChain object - Zedux unwraps all meta nodes before passing actions to the reducer layer.
Returns
The new state or, if the action did not cause a change, the existing state. Don't return undefined from reducers. To return an "empty" value, use null.

See Also