Skip to main content

useReducer

Manage complex state logic with a reducer function.

Import​

import { useReducer } from '@bedrock-core/ui';
import type { Immutable, ReducerSlot } from '@bedrock-core/ui';

Signature​

function useReducer<S, A>(
reducer: (state: Immutable<S>, action: A) => S,
initialState: S
): ReducerSlot<S, A>

Parameters​

ParameterTypeDescription
reducer(state: Immutable<S>, action: A) => SFunction that takes a deeply read-only state view and an action, then returns a replacement
initialStateSThe initial state value

Returns​

An array with two elements:

  1. Current state (Immutable<S>) — A deeply read-only view of the state in TypeScript
  2. Dispatch function ((action: A) => void) - Function to dispatch actions

The dispatch function keeps the same identity across renders of a mounted component. Each action applies the latest reducer to the current state. Dispatches retained after unmount are ignored without calling the reducer.

Usage​

interface State {
count: number;
}

type Action = { type: 'increment' } | { type: 'decrement' } | { type: 'reset' };

function reducer(state: Immutable<State>, action: Action): State {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
return state;
}
}

function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<Panel padding={10} gap={8}>
<Text>{`Count: ${state.count}`}</Text>
<Panel flexDirection={'row'} gap={8}>
<Button flex={1} onPress={() => dispatch({ type: 'increment' })}>
<Text>{'+'}</Text>
</Button>
<Button flex={1} onPress={() => dispatch({ type: 'decrement' })}>
<Text>{'-'}</Text>
</Button>
<Button flex={1} onPress={() => dispatch({ type: 'reset' })}>
<Text>{'Reset'}</Text>
</Button>
</Panel>
</Panel>
);
}

Examples​

Todo list​

type TodoAction =
| { type: 'add'; text: string }
| { type: 'clear' };

function todoReducer(state: Immutable<string[]>, action: TodoAction): string[] {
return action.type === 'clear' ? [] : [...state, action.text];
}
function TodoApp() {
const [todos, dispatch] = useReducer(todoReducer, []);

return (
<Panel padding={10} gap={8}>
<Button enabled={todos.length < 5} onPress={() => dispatch({ type: 'add', text: 'New task' })}>
<Text>{'Add Todo'}</Text>
</Button>
<List max={5} items={todos} row={todo => <Text width={160}>{todo ?? ''}</Text>} />
<Button onPress={() => dispatch({ type: 'clear' })}>
<Text>{'Clear All'}</Text>
</Button>
</Panel>
);
}

List reserves the row capacity required by a compiled screen. The reducer returns new arrays; the read-only state passed into it is never mutated.