Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Managing Complex State with useReducer

Learn how to manage complex state logic using the useReducer hook in React. Handle complex state updates with useReducer for better state management.

jiocoder TeamUpdated Jun 6, 20265 min readReact
Managing Complex State with useReducer

What is useReducer?#

useReducer is an alternative to useState for managing complex state logic in React. It's similar to Redux's reducer pattern and provides a more structured way to handle state updates. While useState is perfect for simple state values, useReducer excels when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

useReducer follows the reducer pattern, which is a functional programming concept. A reducer is a pure function that takes the current state and an action, then returns a new state. This pattern makes state updates predictable and testable.

Installation#

useReducer is part of React core, so no additional installation is needed. It's available in React 16.8+ along with other hooks. To verify your React version:

Code
npm list react

If you need to upgrade:

Code
npm install react@latest react-dom@latest

Basic Syntax#

The useReducer hook takes two arguments: a reducer function and an initial state. It returns an array with the current state and a dispatch function:

Code
import { useReducer } from 'react';

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

// With lazy initialization (optional third argument)
const [state, dispatch] = useReducer(reducer, initialArg, init);

Understanding Reducers#

A reducer function takes two parameters: the current state and an action object. It returns the new state based on the action type:

Code
function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    case 'RESET':
      return { count: 0 };
    default:
      return state;
  }
}

Complete Example: Todo List#

Let's build a comprehensive todo list application using useReducer:

Code
import { useReducer, useState } from 'react';

// Action types as constants (best practice)
const ACTIONS = {
  ADD_TODO: 'ADD_TODO',
  TOGGLE_TODO: 'TOGGLE_TODO',
  DELETE_TODO: 'DELETE_TODO',
  EDIT_TODO: 'EDIT_TODO',
  SET_FILTER: 'SET_FILTER'
};

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

// Initial state
const initialState = {
  todos: [],
  filter: 'ALL' // ALL, ACTIVE, COMPLETED
};

function TodoApp() {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  const [inputValue, setInputValue] = useState('');
  
  const addTodo = () => {
    if (inputValue.trim()) {
      dispatch({
        type: ACTIONS.ADD_TODO,
        payload: { text: inputValue }
      });
      setInputValue('');
    }
  };
  
  const toggleTodo = (id) => {
    dispatch({
      type: ACTIONS.TOGGLE_TODO,
      payload: { id }
    });
  };
  
  const deleteTodo = (id) => {
    dispatch({
      type: ACTIONS.DELETE_TODO,
      payload: { id }
    });
  };
  
  const filteredTodos = state.todos.filter(todo => {
    if (state.filter === 'ACTIVE') return !todo.completed;
    if (state.filter === 'COMPLETED') return todo.completed;
    return true;
  });
  
  return (
    <div className="todo-app">
      <h1>Todo List</h1>
      
      <div className="input-section">
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && addTodo()}
          placeholder="Add a new todo..."
        />
        <button onClick={addTodo}>Add</button>
      </div>
      
      <div className="filters">
        {['ALL', 'ACTIVE', 'COMPLETED'].map(filter => (
          <button
            key={filter}
            onClick={() => dispatch({
              type: ACTIONS.SET_FILTER,
              payload: { filter }
            })}
            className={state.filter === filter ? 'active' : ''}
          >
            {filter}
          </button>
        ))}
      </div>
      
      <ul className="todo-list">
        {filteredTodos.map(todo => (
          <li key={todo.id} className={todo.completed ? 'completed' : ''}>
            <span onClick={() => toggleTodo(todo.id)}>
              {todo.text}
            </span>
            <button onClick={() => deleteTodo(todo.id)}>Delete</button>
          </li>
        ))}
      </ul>
      
      <div className="stats">
        Total: {state.todos.length} | 
        Active: {state.todos.filter(t => !t.completed).length} | 
        Completed: {state.todos.filter(t => t.completed).length}
      </div>
    </div>
  );
}

export default TodoApp;

useReducer with Context#

Combining useReducer with useContext is a powerful pattern for global state management:

Code
import { createContext, useContext, useReducer } from 'react';

const TodoContext = createContext();

function todoReducer(state, action) {
  // ... reducer logic
}

export function TodoProvider({ children }) {
  const [state, dispatch] = useReducer(todoReducer, initialState);
  
  return (
    <TodoContext.Provider value={{ state, dispatch }}>
      {children}
    </TodoContext.Provider>
  );
}

export function useTodos() {
  const context = useContext(TodoContext);
  if (!context) {
    throw new Error('useTodos must be used within TodoProvider');
  }
  return context;
}

// Usage in components
function TodoList() {
  const { state, dispatch } = useTodos();
  // Use state and dispatch
}

Lazy Initialization#

You can pass a function as the third argument to useReducer for lazy initialization:

Code
function init(initialCount) {
  return { count: initialCount };
}

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

function Counter({ initialCount }) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  // ...
}

When to Use useReducer vs useState#

Use useReducer when:

  • You have complex state logic with multiple sub-values
  • The next state depends on the previous state
  • State updates follow predictable patterns
  • You need to optimize performance (dispatch is stable)
  • You want to test state logic separately
  • You're managing form state with multiple fields

Use useState when:

  • State is a simple primitive value (string, number, boolean)
  • State updates are independent
  • You don't need complex update logic
  • State is local to a single component

Best Practices#

  • Use action type constants - Prevents typos and makes refactoring easier
  • Keep reducers pure - No side effects, no mutations
  • Use payload for data - Standardize action structure
  • Handle default case - Return state or throw error
  • Combine with useContext - For global state management
  • Extract action creators - Functions that create actions

Action Creators Pattern#

Code
// Action creators
const todoActions = {
  addTodo: (text) => ({
    type: ACTIONS.ADD_TODO,
    payload: { text }
  }),
  toggleTodo: (id) => ({
    type: ACTIONS.TOGGLE_TODO,
    payload: { id }
  }),
  deleteTodo: (id) => ({
    type: ACTIONS.DELETE_TODO,
    payload: { id }
  })
};

// Usage
dispatch(todoActions.addTodo('New todo'));
dispatch(todoActions.toggleTodo(1));

Testing Reducers#

Reducers are pure functions, making them easy to test:

Code
describe('todoReducer', () => {
  it('should add a todo', () => {
    const state = { todos: [] };
    const action = {
      type: ACTIONS.ADD_TODO,
      payload: { text: 'Test todo' }
    };
    const newState = todoReducer(state, action);
    expect(newState.todos).toHaveLength(1);
    expect(newState.todos[0].text).toBe('Test todo');
  });
  
  it('should toggle a todo', () => {
    const state = {
      todos: [{ id: 1, text: 'Test', completed: false }]
    };
    const action = {
      type: ACTIONS.TOGGLE_TODO,
      payload: { id: 1 }
    };
    const newState = todoReducer(state, action);
    expect(newState.todos[0].completed).toBe(true);
  });
});

useReducer is a powerful tool for managing complex state in React applications. It provides structure, predictability, and testability to your state management. When combined with useContext, it can serve as a lightweight alternative to state management libraries like Redux for many use cases.

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment