Category: react
What Is useReducer?
Published on 27 Oct 2026
Explanation
useReducer manages state through a reducer function that receives the current state and an action, then returns the next state. It is useful when state transitions are related or complex.
Code:
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'reset': return { count: 0 };
default: return state;
}
}
const [state, dispatch] = useReducer(reducer, { count: 0 });
Explanation
Actions describe what happened, while the reducer defines how state changes. This keeps transitions in one predictable place.
Code:
function reducer(state, action) {
if (action.type === 'setName') {
return { ...state, name: action.payload };
}
return state;
}
dispatch({ type: 'setName', payload: 'Asha' });
Explanation
A reducer can manage several related form fields and validation messages without scattering many state update handlers across the component.
Code:
const initialState = { email: '', password: '', submitted: false };
function formReducer(state, action) {
switch (action.type) {
case 'field': return { ...state, [action.name]: action.value };
case 'submit': return { ...state, submitted: true };
default: return state;
}
}
const [form, dispatch] = useReducer(formReducer, initialState);
Explanation
A reducer should be pure: return state based only on its arguments and avoid network calls, timers, or mutations. Perform side effects in event handlers or effects instead.
Code:
function cartReducer(state, action) {
switch (action.type) {
case 'add':
return [...state, action.product]; // New array
case 'clear':
return [];
default:
return state;
}
}
Explanation
useReducer is useful when updates involve multiple fields, many action types, or transitions that are easier to test centrally. For a single simple value, useState is often more direct.
Code:
const initialState = { status: 'idle', data: null, error: null };
function requestReducer(state, action) {
switch (action.type) {
case 'loading': return { status: 'loading', data: null, error: null };
case 'success': return { status: 'success', data: action.data, error: null };
case 'error': return { status: 'error', data: null, error: action.error };
default: return state;
}
}