Curriculum
Course: React
Login

Curriculum

React

Text lesson

useReducer

The useReducer Hook is similar to useState but supports custom state logic. It is useful when managing multiple state values with complex logic.

Syntax

The useReducer Hook takes two arguments.

useReducer(<reducer>, <initialState>)

The reducer function handles your custom state logic, and the initialState can be a simple value but is typically an object.

The useReducer Hook returns the current state and a dispatch method.

Here is an example of useReducer in a counter app:

Example:

import { useReducer } from "react";
import ReactDOM from "react-dom/client";

const initialTodos = [
 {
    id: 1,
    title: "Todo 1",
    complete: false,
 },
 {
    id: 2,
    title: "Todo 2",
    complete: false,
 },
];

const reducer = (state, action) => {
 switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};
 
function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);
 
  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };
 
  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);

This logic manages the status of whether a todo is complete.

By adding more actions, you can include all the functionality to add, delete, and complete todos within a single useReducer Hook.