Skip to main content

createReducer

A factory for creating Redux-style reducers. These reducers can then be passed to createStore() or used directly in React's useReducer() hooks.

Examples

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

const withInitialState = createReducer('initial state')
const withoutInitialState = createReducer()

const withStringActionTypes = createReducer([]).reduce(
'todos/add',
(state, newTodo) => [...state, newTodo]
)

const multipleActions = createReducer([]).reduce(
['todos/reset', 'todos/clear'],
() => []
)

const addTodo = actionFactory<Todo>('todos/add')
const removeTodo = actionFactory<Todo>('todos/add')
const withActionFactories = createReducer([])
.reduce(addTodo, (state, newTodo) => [...state, newTodo])
.reduce(removeTodo, (state, id) => state.filter(todo => todo.id !== id))

const clear = actionFactory('todos/clear')
const mixed = createReducer([])
.reduce(addTodo, (state, newTodo) => [...state, newTodo])
.reduce('todos/remove', (state, id) => state.filter(todo => todo.id !== id))
.reduce(['todos/reset', clear], () => [])

Signature

createReducer = (initialState) => reducerBuilder
initialState

Optional. Can be anything. Default undefined.

This will be set as the initial state of the reducer the first time it runs, e.g. as part of a store creation/hierarchy change.

Returns

See Also