snippettypescriptreactModeratepending
React useReducer -- complex state management without Redux
Viewed 0 times
useReducerdispatchactionreducercomplex statestate machine
browser
Problem
useState becomes unwieldy with complex state that has multiple related fields, conditional transitions, or action-based updates. Multiple setStates cause intermediate renders.
Solution
useReducer centralizes state transitions in a pure reducer function. All state updates are explicit actions with predictable outcomes.
Code Snippets
useReducer with typed actions
type State = { items: Item[]; loading: boolean; error: string | null; page: number };
type Action =
| { type: 'FETCH_START' }
| { type: 'FETCH_SUCCESS'; items: Item[]; page: number }
| { type: 'FETCH_ERROR'; error: string }
| { type: 'REMOVE_ITEM'; id: string };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'FETCH_START':
return { ...state, loading: true, error: null };
case 'FETCH_SUCCESS':
return { ...state, loading: false, items: action.items, page: action.page };
case 'FETCH_ERROR':
return { ...state, loading: false, error: action.error };
case 'REMOVE_ITEM':
return { ...state, items: state.items.filter(i => i.id !== action.id) };
}
}
const [state, dispatch] = useReducer(reducer, {
items: [], loading: false, error: null, page: 1
});
dispatch({ type: 'FETCH_START' });Revisions (0)
No revisions yet.