Repository navigation
useReducer
vinibiavatti1 edited this page Sep 28, 2026
·
2 revisions
An alternative to useState for managing complex state logic or multiple sub-values through dispatched actions. State must be treated as immutable, and the reducer function must be pure (state, action) => newState.
Note: Unlike
useState,useReducerreceives the 2nd argument (arg) and passes it directly to the 3rd argument functioninit(arg). This allowsinitto be declared outside the component as a pure, reusable function.
import { useReducer } from 'react';
// Reducer function (outside component)
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
case 'set_name':
return { ...state, name: action.payload };
default:
return state;
}
}
export const MyComponent = () => {
// Initialization
const [state, dispatch] = useReducer(reducer, {
count: 0,
name: 'John'
});
// Lazy initialization (synchronous)
const [state, dispatch] = useReducer(reducer, 0, arg => ({
count: arg,
name: 'John'
}));
// Dispatching actions
dispatch({ type: 'increment' });
dispatch({ type: 'set_name', payload: 'Jane' });
}- Home
- Functional Components
- Props
- Fragments
- Memoization
- Forward Ref
- Portals
- Suspense
-
Hooks
- State
- Context
- Effect
- Ref
- Performance
- Concurrent
- Form
- Utility
- Custom Hooks