Popular Searches
Popular Course Categories
Popular Courses

useReducer Hook

useReducer Hook

Advanced React Hooks

useReducer Hook in React JS – Complete Detailed Notes

The useReducer Hook is a built-in React Hook used to manage component state. It is particularly useful when state contains multiple related values or when state updates involve several actions and complex logic. Instead of writing state update logic inside multiple event handlers, developers can organize it inside a separate function called a reducer.

The useReducer Hook is an alternative to useState. Both manage state, but useReducer can make complex state transitions more organized, predictable, and easier to maintain.


1. Learning Objectives

After studying this topic, you will be able to:

  • Understand the purpose of the useReducer Hook.
  • Learn its syntax, parameters, and return values.
  • Understand reducers, actions, state, and dispatch.
  • Compare useReducer with useState.
  • Build counters, forms, and task managers using useReducer.
  • Handle multiple state updates using action types.
  • Avoid common mistakes when using reducers.
  • Understand how to use useReducer with Context API.

2. What Is the useReducer Hook?

useReducer is a React Hook that lets a component manage state using a reducer function. The reducer receives the current state and an action, then returns the next state.

Syntax:

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

Explanation:

  • useReducer: The React Hook used to manage state.
  • reducer: A function that determines how the state changes.
  • initialState: The initial state value.
  • state: The current state value.
  • dispatch: A function used to send an action to the reducer.

When you call dispatch(action), React uses the reducer to calculate the next state. React then renders the component with the updated state when needed.

3. Why Do We Need useReducer?

For simple state, useState is usually sufficient. However, as an application grows, a component may have many related state updates, such as adding a task, deleting a task, editing a task, or marking a task as completed.

When update logic is spread across many event handlers, the component can become difficult to understand. The useReducer Hook allows developers to keep related state transition logic in one reducer function.

Example Without useReducer

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  function increment() {
    setCount(value => value + 1);
  }
  function decrement() {
    setCount(value => value - 1);
  }
  function reset() {
    setCount(0);
  }
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}
export default Counter;

Example Using useReducer

import { useReducer } from 'react';
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return 0;
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function Counter() {
  const [count, dispatch] = useReducer(reducer, 0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}
export default Counter;

In the second example, all state transition rules are grouped inside the reducer. The event handlers simply dispatch actions that describe what happened.

4. Understanding the Main Concepts

Concept Meaning Example
State The current data maintained by the component. count
Reducer A function that calculates the next state. reducer(state, action)
Action An object describing an event or requested update. { type: 'increment' }
Dispatch A function that sends an action to the reducer. dispatch({ type: 'increment' })
Initial State The value used to initialize the state. 0 or { count: 0 }

5. How Does useReducer Work?

The useReducer Hook follows a straightforward process:

  1. React initializes the component state using the initial state value.
  2. The user performs an action, such as clicking a button.
  3. The event handler calls dispatch() with an action.
  4. React passes the current state and action to the reducer function.
  5. The reducer calculates and returns the next state.
  6. React renders the component with the new state when necessary.

Basic Flow

User Action
    ↓
dispatch(action)
    ↓
Reducer(state, action)
    ↓
Next State
    ↓
React Re-render
    ↓
Updated UI

6. Basic Syntax of useReducer

import { useReducer } from 'react';
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    default:
      return state;
  }
}
function App() {
  const [count, dispatch] = useReducer(reducer, 0);
  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}
export default App;

In this example, the reducer handles two actions: increment and decrement. Each action returns a new state value.

7. Understanding the Reducer Function

A reducer is a JavaScript function that accepts two parameters:

function reducer(state, action) {
  // Calculate and return the next state
}
  • state: The current state before the update.
  • action: The action dispatched by the component.

A reducer should be a pure function. Given the same state and action, it should return the same result without modifying existing state or causing side effects.

Reducer Example

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

The switch statement checks the action type and determines which state update should occur.

8. Understanding Actions

An action describes what happened or what change is requested. Actions are commonly represented as JavaScript objects with a type property. Additional properties can provide data needed by the reducer.

Examples of Actions

{ type: 'increment' }
{ type: 'decrement' }
{ type: 'reset' }
{ type: 'add_task', text: 'Learn React' }
{ type: 'delete_task', id: 3 }
{ type: 'update_username', name: 'Alex' }

Action names are chosen by the developer. Descriptive names help communicate what each action means.

Action With Additional Data

dispatch({
  type: 'add',
  amount: 5
});

The reducer can read action.amount to determine how much to add.

9. Understanding the dispatch Function

The dispatch function sends an action to the reducer. React uses the reducer's return value as the next state.

Example

const [count, dispatch] = useReducer(reducer, 0);
function handleIncrement() {
  dispatch({ type: 'increment' });
}

You can call dispatch from event handlers to request a state update. It does not return the updated state, and the state variable in the currently running handler remains the snapshot from that render.

10. useReducer With a Number State

A reducer can manage a simple numeric value, such as a counter, score, quantity, or progress indicator.

import { useReducer } from 'react';
function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'decrement':
      return state - 1;
    case 'reset':
      return 0;
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function CounterApp() {
  const [count, dispatch] = useReducer(counterReducer, 0);
  return (
    <div>
      <h2>Counter Application</h2>
      <p>Current Count: {count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}
export default CounterApp;

Expected Output

  • Initially, the counter displays 0.
  • Clicking Increment increases the count by 1.
  • Clicking Decrement decreases the count by 1.
  • Clicking Reset changes the count back to 0.

11. useReducer With an Object State

The useReducer Hook is especially useful when state contains multiple related properties.

import { useReducer } from 'react';
const initialState = {
  name: 'Alex',
  age: 25
};
function userReducer(state, action) {
  switch (action.type) {
    case 'change_name':
      return {
        ...state,
        name: action.name
      };
    case 'increase_age':
      return {
        ...state,
        age: state.age + 1
      };
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function UserProfile() {
  const [user, dispatch] = useReducer(userReducer, initialState);
  return (
    <div>
      <h2>User Profile</h2>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={() => dispatch({ type: 'change_name', name: 'Jordan' })}>Change Name</button>
      <button onClick={() => dispatch({ type: 'increase_age' })}>Increase Age</button>
    </div>
  );
}
export default UserProfile;

The spread operator ...state copies the existing properties into a new object before the selected property is updated. This prevents direct mutation and preserves the other fields.

12. useReducer With Form Inputs

Forms often contain multiple related fields, such as a username, email address, and password. A reducer can centralize updates for these fields.

import { useReducer } from 'react';
const initialState = {
  username: '',
  email: ''
};
function formReducer(state, action) {
  switch (action.type) {
    case 'update_field':
      return {
        ...state,
        [action.field]: action.value
      };
    case 'reset':
      return initialState;
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function RegistrationForm() {
  const [form, dispatch] = useReducer(formReducer, initialState);
  function handleChange(event) {
    dispatch({
      type: 'update_field',
      field: event.target.name,
      value: event.target.value
    });
  }
  function handleSubmit(event) {
    event.preventDefault();
    alert(`Username: ${form.username}, Email: ${form.email}`);
  }
  return (
    <form onSubmit={handleSubmit}>
      <h2>Registration Form</h2>
      <label>Username:</label>
      <input name="username" value={form.username} onChange={handleChange} required />
      <label>Email:</label>
      <input name="email" type="email" value={form.email} onChange={handleChange} required />
      <button type="submit">Submit</button>
      <button type="button" onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </form>
  );
}
export default RegistrationForm;

In this example, the same update_field action updates either field. The field property specifies which field to update, while value contains the new input value.

13. useReducer With an Array State

A reducer can also manage arrays, such as shopping cart items, task lists, or notifications. The array should be updated immutably.

import { useReducer } from 'react';
const initialTasks = [
  { id: 1, text: 'Learn React', completed: false }
];
function taskReducer(state, action) {
  switch (action.type) {
    case 'add':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ];
    case 'toggle':
      return state.map(task =>
        task.id === action.id
          ? { ...task, completed: !task.completed }
          : task
      );
    case 'delete':
      return state.filter(task => task.id !== action.id);
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function TaskList() {
  const [tasks, dispatch] = useReducer(taskReducer, initialTasks);
  function addTask() {
    dispatch({
      type: 'add',
      id: crypto.randomUUID(),
      text: 'Practice useReducer'
    });
  }
  return (
    <div>
      <h2>Task List</h2>
      <button onClick={addTask}>Add Task</button>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            <span>{task.text} - {task.completed ? 'Completed' : 'Pending'}</span>
            <button onClick={() => dispatch({ type: 'toggle', id: task.id })}>Toggle</button>
            <button onClick={() => dispatch({ type: 'delete', id: task.id })}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}
export default TaskList;

The reducer uses map() to update a task and filter() to remove one. Both operations create a new array rather than modifying the existing state.

14. The Initial State in useReducer

The second argument to useReducer provides the initial state when the component initializes.

const initialState = {
  count: 0,
  username: 'Guest'
};
const [state, dispatch] = useReducer(reducer, initialState);

React saves the initial state for that component instance. Changes to the initialState variable on later renders do not automatically reset the reducer state.

15. Lazy Initialization With the Third Argument

If creating the initial state requires an expensive calculation, useReducer supports a third argument called an initializer function.

const [state, dispatch] = useReducer(reducer, initialArg, init);
  • reducer: Calculates the next state.
  • initialArg: The argument passed to the initializer.
  • init: A function that calculates and returns the initial state.

Example

import { useReducer } from 'react';
function createInitialState(initialCount) {
  return {
    count: initialCount,
    history: []
  };
}
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {
        count: state.count + 1,
        history: [...state.history, state.count + 1]
      };
    default:
      return state;
  }
}
function Counter() {
  const [state, dispatch] = useReducer(reducer, 10, createInitialState);
  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
    </div>
  );
}
export default Counter;

Here, createInitialState receives 10 and returns the initial state object. Passing the initializer function avoids calling that initialization calculation on every render. The initializer should be pure.

16. useReducer vs useState

Feature useState useReducer
Basic purpose Manages a state value. Manages state using a reducer function.
State updates Uses a setter function. Uses a dispatch function and actions.
Update logic Often placed in event handlers. Centralized in a reducer.
Best suited for Simple or independent state values. Complex state transitions or related updates.
State shape Any type, including objects and arrays. Any type, including objects and arrays.
Learning curve Usually simpler for beginners. Requires understanding reducers and actions.
Boilerplate Usually less for simple updates. May require more setup for simple state.
Immutability Important for objects and arrays. Important for objects and arrays.

Important: useReducer is not automatically faster than useState. Choose the Hook that makes the state logic easiest to understand and maintain.

17. When Should You Use useReducer?

Consider useReducer when:

  • A component has multiple related state updates.
  • Several event handlers update the same state in different ways.
  • State transitions are easier to describe using named actions.
  • The state is an object or array with coordinated updates.
  • You want to test state transition logic independently from the UI.
  • A form, task manager, shopping cart, or multi-step interface has complex state behavior.

For a simple toggle or a single independent input, useState may be more straightforward.

18. Common Mistakes When Using useReducer

Mistake 1: Mutating State Directly

Incorrect:

function reducer(state, action) {
  state.count += 1;
  return state;
}

Correct:

function reducer(state, action) {
  return {
    ...state,
    count: state.count + 1
  };
}

Always return a new object or array when changing object or array state.

Mistake 2: Forgetting to Return the Next State

Every supported action must return the correct next state. If a reducer accidentally returns undefined, the component may fail when it tries to read properties from the state.

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return state + 1;
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}

Mistake 3: Using the Wrong Action Type

The dispatched action type must match the reducer's cases.

dispatch({ type: 'increment' });

If the reducer handles only 'increase', the action 'increment' will not match. Use consistent, descriptive action names.

Mistake 4: Forgetting to Preserve Existing Object Properties

Incorrect:

return { count: state.count + 1 };

If the state also contains username, that property is lost from the returned object.

Correct:

return {
  ...state,
  count: state.count + 1
};

Mistake 5: Dispatching During Rendering

Do not unconditionally call dispatch() while rendering a component. It can trigger repeated renders and cause an error such as “Too many re-renders.” Dispatch actions in event handlers or other appropriate logic.

Mistake 6: Expecting State to Change Immediately

After calling dispatch(), the state variable in the currently running function still represents the previous render's snapshot. Use the updated state on the next render.

Mistake 7: Performing Side Effects Inside the Reducer

Reducers should be pure functions. Avoid making API requests, modifying the DOM, setting timers, or changing external variables inside the reducer. Handle side effects in suitable event handlers or Effects.

19. Using useReducer With Context API

For larger applications, you can combine useReducer with React Context. The reducer manages state updates, while Context makes the state and dispatch function available to components deeper in the component tree without passing them through every intermediate component.

Basic Example

import { createContext, useContext, useReducer } from 'react';
const CountContext = createContext(null);
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return state + 1;
    case 'reset':
      return 0;
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function CounterProvider({ children }) {
  const [count, dispatch] = useReducer(reducer, 0);
  return (
    <CountContext.Provider value={{ count, dispatch }}>
      {children}
    </CountContext.Provider>
  );
}
function CounterControls() {
  const context = useContext(CountContext);
  if (context === null) {
    throw new Error('CounterControls must be inside CounterProvider');
  }
  const { count, dispatch } = context;
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
    </div>
  );
}
function App() {
  return (
    <CounterProvider>
      <CounterControls />
    </CounterProvider>
  );
}
export default App;

For a larger application, consider separating state and dispatch into two contexts when that better fits your component structure. This can help components that only dispatch actions avoid subscribing to state changes through the same context value.

20. Best Practices for useReducer

  • Keep reducer functions pure and predictable.
  • Use descriptive action names, such as added, deleted, and updated.
  • Keep related state transition logic inside the reducer.
  • Return a valid next state for every supported action.
  • Do not mutate existing state objects or arrays.
  • Use the spread operator or immutable array methods where appropriate.
  • Handle unknown actions deliberately, often by throwing an error.
  • Keep side effects outside the reducer.
  • Use useState when the state logic is simple.
  • Consider combining useReducer with Context for shared state across a component tree.
  • Test reducers independently using different states and actions.

21. Practical Project: Shopping Cart With useReducer

Build a basic shopping cart where users can add products, increase quantities, decrease quantities, and remove products. This exercise demonstrates how a reducer can manage several related actions.

Project Requirements

  1. Create an initial cart containing a product array.
  2. Use useReducer to manage the cart.
  3. Add an action to increase a product quantity.
  4. Add an action to decrease a product quantity.
  5. Add an action to remove a product.
  6. Calculate the total price from the current cart state.
  7. Use immutable updates for every state transition.

Sample Code

import { useReducer } from 'react';
const initialCart = [
  { id: 1, name: 'Keyboard', price: 1500, quantity: 1 },
  { id: 2, name: 'Mouse', price: 700, quantity: 1 }
];
function cartReducer(state, action) {
  switch (action.type) {
    case 'increase':
      return state.map(item =>
        item.id === action.id
          ? { ...item, quantity: item.quantity + 1 }
          : item
      );
    case 'decrease':
      return state
        .map(item =>
          item.id === action.id
            ? { ...item, quantity: item.quantity - 1 }
            : item
        )
        .filter(item => item.quantity > 0);
    case 'remove':
      return state.filter(item => item.id !== action.id);
    default:
      throw new Error(`Unknown action: ${action.type}`);
  }
}
function ShoppingCart() {
  const [cart, dispatch] = useReducer(cartReducer, initialCart);
  const total = cart.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  );
  return (
    <div>
      <h2>Shopping Cart</h2>
      {cart.length === 0 ? (
        <p>Your cart is empty.</p>
      ) : (
        <ul>
          {cart.map(item => (
            <li key={item.id}>
              {item.name} - ₹{item.price} × {item.quantity}
              <button onClick={() => dispatch({ type: 'increase', id: item.id })}>+</button>
              <button onClick={() => dispatch({ type: 'decrease', id: item.id })}>-</button>
              <button onClick={() => dispatch({ type: 'remove', id: item.id })}>Remove</button>
            </li>
          ))}
        </ul>
      )}
      <h3>Total: ₹{total}</h3>
    </div>
  );
}
export default ShoppingCart;

Project explanation: The reducer manages product quantity changes and item removal. The total price is calculated directly from the current cart, so a separate state variable and Effect are not needed for the total.

22. Interview Questions and Answers

Q1. What is the useReducer Hook?

useReducer is a React Hook that manages state through a reducer function and dispatched actions.

Q2. What does useReducer return?

It returns an array containing the current state and the dispatch function.

Q3. What is a reducer function?

A reducer is a pure function that receives the current state and an action, then returns the next state.

Q4. What is dispatch in React?

dispatch sends an action to the reducer to request a state update.

Q5. What is an action?

An action describes an event or requested state transition. It is commonly an object with a type property and optional data.

Q6. What is the difference between useState and useReducer?

useState updates state through a setter function, while useReducer centralizes state transition logic in a reducer and updates state by dispatching actions.

Q7. Can useReducer manage arrays and objects?

Yes. It can manage any JavaScript state value, including numbers, strings, arrays, objects, and other supported values.

Q8. Why should a reducer be pure?

A pure reducer produces predictable results, avoids side effects, and safely handles React's development checks.

Q9. Can we use useReducer for form handling?

Yes. It can manage related form fields, validation status, submission state, and form reset actions.

Q10. What is lazy initialization in useReducer?

Lazy initialization uses the optional third argument, an initializer function, to calculate the initial state only during initialization rather than recalculating it on every render.

Q11. Can useReducer be combined with Context?

Yes. Context can provide the reducer's state and dispatch function to components throughout a component tree.

Q12. Does dispatch immediately change the state variable?

No. Dispatch requests an update. The state variable in the current render remains the existing snapshot until React renders with the next state.

23. Practice Exercises

  1. Create a counter using useReducer with increment, decrement, and reset actions.
  2. Create a user profile that updates a person's name and age.
  3. Build a form with name, email, and phone fields using one reducer.
  4. Create a task list with add, complete, and delete actions.
  5. Build a shopping cart with increase and decrease quantity actions.
  6. Use the third argument of useReducer to initialize a state object.
  7. Combine useReducer and Context to share state with nested components.
  8. Write unit tests for a reducer by checking its output for different actions.

24. Quick Revision Checklist

  • ☑ useReducer manages state using a reducer function.
  • ☑ Its basic syntax is useReducer(reducer, initialState).
  • ☑ It returns the current state and a dispatch function.
  • ☑ Actions describe requested state transitions.
  • ☑ Reducers calculate and return the next state.
  • ☑ Reducers should be pure functions.
  • ☑ Existing objects and arrays should not be mutated.
  • ☑ Every supported action should return a valid next state.
  • ☑ The optional third argument supports lazy initialization.
  • ☑ useReducer can manage counters, forms, task lists, and shopping carts.
  • ☑ It can be combined with Context for shared state.
  • ☑ useState remains a good choice for simpler state logic.

25. Official React Documentation

26. React JS Training and Course Demo

To develop your React JS skills further, explore the course details and register for a course demo to learn more about the training.

27. Conclusion

The useReducer Hook is a valuable tool for managing React state when multiple related updates need organized logic. It separates the description of an action from the logic that calculates the next state. By understanding reducers, actions, dispatch, immutable updates, and lazy initialization, developers can build more maintainable components.

Use useReducer when it makes state transitions easier to understand, and use useState when a simpler solution is sufficient. Practice with counters, forms, task managers, and shopping carts to strengthen your understanding of this important React Hook.

Previous Next
whatsapp