0
0
ReactHow-ToBeginner · 3 min read

How to Dispatch Action in useReducer in React

In React, you dispatch an action in useReducer by calling the dispatch function with an action object, usually containing a type property. This tells the reducer how to update the state based on the action received.
📐

Syntax

The dispatch function is called with an action object. This object typically has a type property that describes what change to make, and optionally other data.

Example action object: { type: 'increment' }

javascript
dispatch({ type: 'ACTION_TYPE', payload: someData })
💻

Example

This example shows a counter using useReducer. The dispatch function is called with actions to increase or decrease the count.

javascript
import React, { 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 };
    default:
      return state;
  }
}

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

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
    </div>
  );
}
Output
Count: 0 (initially) Clicking Increment increases count by 1 Clicking Decrement decreases count by 1
⚠️

Common Pitfalls

  • Not passing an object with a type property to dispatch causes the reducer to not recognize the action.
  • Mutating state directly inside the reducer instead of returning a new state object can cause bugs.
  • Forgetting to handle an action type in the reducer leads to unexpected state.
javascript
/* Wrong: dispatching a string instead of an object */
dispatch('increment');

/* Right: dispatching an action object */
dispatch({ type: 'increment' });
📊

Quick Reference

Remember these points when dispatching actions in useReducer:

  • Always dispatch an object with a type key.
  • Use dispatch inside event handlers or effects to trigger state changes.
  • The reducer function decides how state updates based on the action type.

Key Takeaways

Use the dispatch function with an action object containing a type to update state in useReducer.
Always return a new state object from the reducer; never mutate state directly.
Dispatch actions inside event handlers to trigger state changes.
Ensure your reducer handles all expected action types to avoid unexpected state.
The action object can include extra data in a payload for flexible updates.