Migrating from useReducer + Context
If you’ve outgrown plain useState and built a useReducer + Context setup, your codebase is already action-shaped. input-actions is the same idea with batteries included: a generic action vocabulary, a built-in pure reducer, async lifecycle, state machines, and bindings — all sharing one dispatch surface.
The mapping in one screen
Section titled “The mapping in one screen”// Before — useReducer + Contexttype State = { count: number; user: { name: string } };type Action = | { type: 'INCREMENT' } | { type: 'DECREMENT' } | { type: 'SET_NAME'; name: string };
function reducer(state: State, action: Action): State { switch (action.type) { case 'INCREMENT': return { ...state, count: state.count + 1 }; case 'DECREMENT': return { ...state, count: state.count - 1 }; case 'SET_NAME': return { ...state, user: { ...state.user, name: action.name } }; default: return state; }}
const StateCtx = createContext<State>(null!);const DispatchCtx = createContext<React.Dispatch<Action>>(null!);
function Provider({ children }) { const [state, dispatch] = useReducer(reducer, { count: 0, user: { name: '' } }); return ( <StateCtx.Provider value={state}> <DispatchCtx.Provider value={dispatch}>{children}</DispatchCtx.Provider> </StateCtx.Provider> );}
function Counter() { const state = useContext(StateCtx); const dispatch = useContext(DispatchCtx); return ( <button onClick={() => dispatch({ type: 'INCREMENT' })}> {state.count} </button> );}// After — StoreProvider + useStore + useActionsimport { StoreProvider, createSimpleStore, useStore, useActions,} from '@input-actions/core';
const store = createSimpleStore({ count: 0, user: { name: '' } });
function App() { return ( <StoreProvider store={store}> <Counter /> </StoreProvider> );}
function Counter() { const count = useStore((s) => s.count); const actions = useActions(); return ( <button onClick={actions(['action/increment', ['count']])}> {count} </button> );}Half the code, two fewer contexts, no reducer to maintain.
Concept mapping
Section titled “Concept mapping”| useReducer + Context | input-actions |
|---|---|
Action shape { type: '…', …payload } | Tuple ['action/…', path, value?] |
Custom reducer(state, action) | applyAction — pure reducer shared across adapters (ADR 0015) |
useReducer(reducer, initial) | createSimpleStore(initial) (or any adapter) |
| Two contexts: state + dispatch | One <StoreProvider store={store}> |
useContext(StateCtx) | useStore((s) => …) with selector subscriptions |
useContext(DispatchCtx) | useActions() for event handlers, useDispatch() for programmatic dispatch |
| Custom action types per slice | Reuse the generic vocabulary (save, toggle, push, merge, …) |
| Thunks / saga middleware | asyncHandlers on the provider, with strategies (prevent, cancel, queue, debounce, allow) |
| Discriminated-union exhaustiveness check | The Action type union — same TypeScript benefit |
Recipe
Section titled “Recipe”-
Move your reducer’s state shape into a
createSimpleStoreinitial value.// beforeconst initial: State = { count: 0, user: { name: '' } };const [state, dispatch] = useReducer(reducer, initial);// afterconst store = createSimpleStore({ count: 0, user: { name: '' } });No reducer needed — the generic
applyActionreducer knows how to interpretaction/save,action/increment,action/push, etc. against any path in your state. -
Replace your provider’s two contexts with one
<StoreProvider>.// before<StateCtx.Provider value={state}><DispatchCtx.Provider value={dispatch}>{children}</DispatchCtx.Provider></StateCtx.Provider>// after<StoreProvider store={store}>{children}</StoreProvider>One provider, one context, no value-stability boilerplate.
-
Translate each action variant into the generic vocabulary.
// beforecase 'INCREMENT': return { ...state, count: state.count + 1 };case 'DECREMENT': return { ...state, count: state.count - 1 };case 'SET_NAME': return { ...state, user: { ...state.user, name: action.name } };case 'TOGGLE_DARK': return { ...state, dark: !state.dark };case 'ADD_TODO': return { ...state, todos: [...state.todos, action.todo] };case 'CLEAR': return initial;→
// after — dispatched at call sites, not handled in a reduceractions(['action/increment', ['count']])actions(['action/decrement', ['count']])actions(['action/save', ['user', 'name'], 'event/target.value'])actions(['action/toggle', ['dark']])actions(['action/push', ['todos'], newTodo])actions(['action/reset'])The dispatcher knows the path and the operation; the reducer doesn’t need a case per slice.
-
Replace reads.
// beforeconst state = useContext(StateCtx);const name = state.user.name;// afterconst name = useStore((s) => s.user.name);Selector subscriptions: this component re-renders only when
s.user.namechanges, not on every dispatch. With the bareuseContext(StateCtx), every consumer re-renders on every state update — the well-known context-fanout problem. -
Replace dispatches.
// beforeconst dispatch = useContext(DispatchCtx);<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>// afterconst actions = useActions();<button onClick={actions(['action/increment', ['count']])}>+</button>
When your action types don’t map to the generic vocabulary
Section titled “When your action types don’t map to the generic vocabulary”Most custom action types in a useReducer codebase fall into one of these categories:
Multi-step state changes
Section titled “Multi-step state changes”Your reducer might handle one action that touches several slices:
// beforecase 'CHECKOUT_COMPLETE': return { ...state, order: action.order, cart: { lines: [] }, ui: { ...state.ui, modalOpen: false }, };Express as a batch — same composition, but the parts are inspectable:
// afteractions([ ['action/save', ['order'], confirmedOrder], ['action/save', ['cart'], { lines: [] }], ['action/save', ['ui', 'modalOpen'], false],])Or, if the same combination fires from many places, register it as a bound action and reference by id.
Async side-effect actions (thunks)
Section titled “Async side-effect actions (thunks)”// before — redux thunk stylefunction submitForm(data) { return async (dispatch) => { dispatch({ type: 'SUBMIT_START' }); try { const result = await api.submit(data); dispatch({ type: 'SUBMIT_SUCCESS', result }); } catch (e) { dispatch({ type: 'SUBMIT_ERROR', error: e.message }); } };}→
// after — handler is the data, lifecycle is automaticconst asyncHandlers = { submitForm: async (data, { signal }) => api.submit(data),};
<StoreProvider store={store} asyncHandlers={asyncHandlers}>
// dispatch site:actions(['action/async', 'submit', 'submitForm', { strategy: 'prevent', onSuccess: [ ['action/save', ['notice'], 'Order placed!'],]}, formData])The library tracks _async.submit.status automatically. Five concurrency strategies (prevent, cancel, queue, debounce, allow) cover the patterns thunks usually handle by hand.
State-machine-shaped actions
Section titled “State-machine-shaped actions”// before — booleans encoding implicit statescase 'START_CONNECTING': return { ...state, isConnecting: true, error: null };case 'CONNECTED': return { ...state, isConnecting: false, isConnected: true };case 'CONNECTION_ERROR': return { ...state, isConnecting: false, error: action.msg };case 'DISCONNECT': return { ...state, isConnected: false };→
// after — an explicit FSMconst connectionMachine = { name: 'connection', initialState: 'disconnected', states: { disconnected: { allowedTransitions: ['connecting'] }, connecting: { allowedTransitions: ['connected', 'disconnected'] }, connected: { allowedTransitions: ['disconnected'] }, },};
<StoreProvider store={store} stateMachines={[connectionMachine]}>
// dispatch site:actions(['machine/transition', 'connection', 'connecting'])Invalid transitions are blocked by the validator. See the machine actions concept page.
TypeScript: where to put the action union
Section titled “TypeScript: where to put the action union”In a useReducer codebase, you usually have a discriminated Action union and an exhaustive switch. The TypeScript value of that union is exhaustiveness checking — adding a new action variant flags every switch that doesn’t handle it.
input-actions ships its own Action union covering every variant the library understands. Your custom union goes away; the library’s union takes over. If you’re modelling app-specific flows (multi-step transitions, async lifecycles), encode them with state machines and async handlers — those are how the library expresses “operations” without a per-app action enum.
For app-specific guards on dispatch payloads, write a small typed helper:
import type { Action } from '@input-actions/core';
export const saveUserName = (name: string): Action => ['action/save', ['user', 'name'], name];Helpers like this give you the same call-site type-safety a custom action union did, without owning a reducer.
Pitfall fixes
Section titled “Pitfall fixes”| useReducer + Context pitfall | input-actions fix |
|---|---|
| Context fan-out re-renders (every consumer re-renders on every dispatch) | useStore((s) => …) subscribes to slices, not the whole store |
| Reducer-state coupling (adding a slice means a new action variant) | action/save + path addresses any nested slice; no new action types needed |
| Two contexts to wire | One <StoreProvider> |
| Thunk middleware setup | Async handlers + strategies built in |
| Booleans encoding state machines | First-class FSM with validated transitions |
Where to go next
Section titled “Where to go next”- Action types reference — every action the library understands.
- Machine actions concept — for the FSM-shaped pieces of your old reducer.
- Action bindings quickstart — hoist commonly-used dispatches into a registry.
- Building a checkout flow — a real example using FSM + async + bindings together.