</>
Skip to content
React lessons (22/47)

React — useReducer

Basic useReducer

import { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 };
        case 'decrement':
            return { count: state.count - 1 };
        case 'reset':
            return initialState;
        default:
            throw new Error();
    }
}

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

    return (
        <div>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({ type: 'increment' })}>+</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
            <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
        </div>
    );
}

useReducer with Actions

const initialState = {
    todos: [],
    filter: 'all'
};

function todoReducer(state, action) {
    switch (action.type) {
        case 'ADD_TODO':
            return {
                ...state,
                todos: [...state.todos, {
                    id: Date.now(),
                    text: action.payload,
                    completed: false
                }]
            };
        case 'TOGGLE_TODO':
            return {
                ...state,
                todos: state.todos.map(todo =>
                    todo.id === action.payload
                        ? { ...todo, completed: !todo.completed }
                        : todo
                )
            };
        case 'DELETE_TODO':
            return {
                ...state,
                todos: state.todos.filter(todo => todo.id !== action.payload)
            };
        case 'SET_FILTER':
            return {
                ...state,
                filter: action.payload
            };
        default:
            return state;
    }
}

function TodoApp() {
    const [state, dispatch] = useReducer(todoReducer, initialState);

    return (
        <div>
            <input
                onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                        dispatch({ type: 'ADD_TODO', payload: e.target.value });
                        e.target.value = '';
                    }
                }}
            />
            <div>
                <button onClick={() => dispatch({ type: 'SET_FILTER', payload: 'all' })}>All</button>
                <button onClick={() => dispatch({ type: 'SET_FILTER', payload: 'active' })}>Active</button>
                <button onClick={() => dispatch({ type: 'SET_FILTER', payload: 'completed' })}>Completed</button>
            </div>
            <ul>
                {state.todos.map(todo => (
                    <li key={todo.id}>
                        <span
                            onClick={() => dispatch({ type: 'TOGGLE_TODO', payload: todo.id })}
                            style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
                        >
                            {todo.text}
                        </span>
                        <button onClick={() => dispatch({ type: 'DELETE_TODO', payload: todo.id })}>
                            Delete
                        </button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

Mini Practice

Write React code that:

  1. Creates a basic useReducer
  2. Implements multiple actions
  3. Manages complex state
  4. Combines useReducer with useContext

Up Next

Next: Learn about useMemo hook.

Related Topics

Frequently Asked Questions about useReducer

What is useReducer in React?

useReducer is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn useReducer?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn useReducer.

Why is useReducer important in React?

useReducer is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.