What is Redux Dispatch in React?

This article provides a clear and concise guide to understanding Redux Dispatch in React applications. You will learn what the dispatch function is, how it triggers state changes by sending actions to the Redux store, and how to implement it in your code using modern React Redux hooks.

Understanding the Role of Dispatch in Redux

In Redux, the state of your application is read-only. The only way to change the state is to emit an “action,” which is a plain JavaScript object describing what happened. The dispatch function is the mechanism Redux provides to send these actions to the Redux store.

Without dispatching an action, the Redux store has no way of knowing that an event has occurred or that the state needs to be updated. It acts as the delivery service in the Redux data flow:

\[\text{UI Event} \longrightarrow \text{Dispatch(Action)} \longrightarrow \text{Reducer} \longrightarrow \text{New Store State} \longrightarrow \text{UI Update}\]

How Redux Dispatch Works

The dispatch function accepts an action object as its argument. An action must have a type property (usually a string) that describes the event, and it can optionally carry a payload containing data needed for the update.

Here is a basic example of an action object:

const addNotificationAction = {
  type: 'notifications/add',
  payload: 'You have a new message'
};

To trigger this action and update the state, you pass it to the dispatch function:

dispatch(addNotificationAction);

Once dispatch is called, the Redux store automatically passes the current state and the dispatched action to your reducer functions. The reducers calculate the new state, the store updates, and the React components re-render to reflect the changes.

Using useDispatch in React

In modern React applications, the easiest way to access the dispatch function is through the useDispatch hook provided by the react-redux library.

Below is a practical example of how to use useDispatch in a React component to update a simple counter state:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';

function Counter() {
  // 1. Initialize the dispatch hook
  const dispatch = useDispatch();
  
  // Access the current count from the store
  const count = useSelector((state) => state.counter.value);

  return (
    <div>
      <p>Count: {count}</p>
      
      {/* 2. Dispatch actions on button clicks */}
      <button onClick={() => dispatch({ type: 'counter/increment' })}>
        Increment
      </button>
      
      <button onClick={() => dispatch({ type: 'counter/decrement' })}>
        Decrement
      </button>
      
      <button onClick={() => dispatch({ type: 'counter/incrementByAmount', payload: 5 })}>
        Add 5
      </button>
    </div>
  );
}

export default Counter;

Key Takeaways