Skip to content

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, useReducer receives the 2nd argument (arg) and passes it directly to the 3rd argument function init(arg). This allows init to 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' });
}

Clone this wiki locally