Skip to content
React

useReducer

Complex state management.

By EZ4Code Team
reacthook

Code

import { useReducer } from 'react';

// Define reducer
const initialState = {
    items: [],
    loading: false,
    error: null,
};

function reducer(state, action) {
    switch (action.type) {
        case 'FETCH_START':
            return { ...state, loading: true, error: null };
        case 'FETCH_SUCCESS':
            return { ...state, loading: false, items: action.payload };
        case 'FETCH_ERROR':
            return { ...state, loading: false, error: action.payload };
        case 'ADD_ITEM':
            return { ...state, items: [...state.items, action.payload] };
        case 'REMOVE_ITEM':
            return {
                ...state,
                items: state.items.filter(i => i.id !== action.payload),
            };
        default:
            return state;
    }
}

function ItemList() {
    const [state, dispatch] = useReducer(reducer, initialState);

    const fetchItems = async () => {
        dispatch({ type: 'FETCH_START' });
        try {
            const res = await fetch('/api/items');
            const data = await res.json();
            dispatch({ type: 'FETCH_SUCCESS', payload: data });
        } catch (err) {
            dispatch({ type: 'FETCH_ERROR', payload: err.message });
        }
    };

    useEffect(() => { fetchItems(); }, []);

    if (state.loading) return <div>Loading...</div>;
    if (state.error) return <div>Error: {state.error}</div>;

    return (
        <ul>
            {state.items.map(item => (
                <li key={item.id}>{item.name}</li>
            ))}
        </ul>
    );
}

Explanation

useReducer is suitable for complex state logic; actions trigger state transitions; reducers return new state.

More React Snippets