Hint
Complex state logic with multiple sub-values or when next state depends on action type — like Redux at component level
const [state, dispatch] = useReducer(reducer, initialState);
const initialState = { count: 0, loading: false, error: null };
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT': return { ...state, count: state.count + 1 };
case 'SET_LOADING': return { ...state, loading: action.payload };
case 'SET_ERROR': return { ...state, error: action.payload };
case 'RESET': return initialState;
default: return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
);
}
Choose useReducer when: