Skip to content

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.

// Before — useReducer + Context
type 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 + useActions
import {
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.

useReducer + Contextinput-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 + dispatchOne <StoreProvider store={store}>
useContext(StateCtx)useStore((s) => …) with selector subscriptions
useContext(DispatchCtx)useActions() for event handlers, useDispatch() for programmatic dispatch
Custom action types per sliceReuse the generic vocabulary (save, toggle, push, merge, …)
Thunks / saga middlewareasyncHandlers on the provider, with strategies (prevent, cancel, queue, debounce, allow)
Discriminated-union exhaustiveness checkThe Action type union — same TypeScript benefit
  1. Move your reducer’s state shape into a createSimpleStore initial value.

    // before
    const initial: State = { count: 0, user: { name: '' } };
    const [state, dispatch] = useReducer(reducer, initial);
    // after
    const store = createSimpleStore({ count: 0, user: { name: '' } });

    No reducer needed — the generic applyAction reducer knows how to interpret action/save, action/increment, action/push, etc. against any path in your state.

  2. 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.

  3. Translate each action variant into the generic vocabulary.

    // before
    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 } };
    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 reducer
    actions(['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.

  4. Replace reads.

    // before
    const state = useContext(StateCtx);
    const name = state.user.name;
    // after
    const name = useStore((s) => s.user.name);

    Selector subscriptions: this component re-renders only when s.user.name changes, not on every dispatch. With the bare useContext(StateCtx), every consumer re-renders on every state update — the well-known context-fanout problem.

  5. Replace dispatches.

    // before
    const dispatch = useContext(DispatchCtx);
    <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
    // after
    const 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:

Your reducer might handle one action that touches several slices:

// before
case '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:

// after
actions([
['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.

// before — redux thunk style
function 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 automatic
const 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.

// before — booleans encoding implicit states
case '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 FSM
const 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.

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.

useReducer + Context pitfallinput-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 wireOne <StoreProvider>
Thunk middleware setupAsync handlers + strategies built in
Booleans encoding state machinesFirst-class FSM with validated transitions