React › useReducer & Complex State Logic
How would you manage a multi step form's state using useReducer instead of several separate useState calls?
IntermediateAnswer
A multi step form often has many related pieces of state, like the current step number and each field's value, that change together in predictable ways. useReducer lets you organize all of these updates through clearly named actions, like next step or update field, keeping the related logic together instead of spread across many separate state variables.
function formReducer(state, action) {
switch (action.type) {
case 'updateField':
return { ...state, [action.field]: action.value };
case 'nextStep':
return { ...state, step: state.step + 1 };
default:
return state;
}
}
const [formState, dispatch] = useReducer(formReducer, { step: 1, name: '', email: '' });Real-world example A job application form with several steps keeps all of its related state and update logic organized in one reducer, making it much easier to add a new field or step later without touching several separate useState calls scattered throughout the component.