ReactEasy

What is Dispatch?

dispatch is the store method that sends an action to Redux: dispatch({ type: "cart/cleared" }) or dispatch(cartCleared()). The action passes through middleware and then the reducers, which produce the new state, and subscribers such as useSelector re-render if their selected data changed. In React you get it with useDispatch().

What happens on dispatch

  1. Middleware runs in order: it can log, transform, delay or stop the action, or handle functions (thunks).
  2. The root reducer computes the next state.
  3. The store notifies subscribers.
  4. Components whose useSelector result changed re-render.

Dispatching async work

With the thunk middleware (included by configureStore), you can dispatch a function: dispatch(fetchUser(id)). createAsyncThunk returns a promise you can await and .unwrap() to get the result or throw on failure.

In React

  • const dispatch = useDispatch() (or a typed useAppDispatch).
  • dispatch is stable, so it is safe in dependency arrays.
  • Call it in event handlers or effects, never during render.

useReducer

React's useReducer also returns a dispatch with the same idea, scoped to one component.

Pattern

Components dispatch high-level events ("checkout submitted"); thunks or listener middleware coordinate the follow-up work (API calls, navigation, analytics).

Code example

tsx
1import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
2import { useDispatch } from "react-redux";
3
4export const placeOrder = createAsyncThunk("orders/place", async (cartId: string) => {
5 const res = await fetch(`/api/orders`, { method: "POST", body: JSON.stringify({ cartId }) });
6 if (!res.ok) throw new Error("Order failed");
7 return (await res.json()) as { orderId: string };
8});
9
10export const ordersSlice = createSlice({
11 name: "orders",
12 initialState: { lastOrderId: null as string | null, error: null as string | null },
13 reducers: {},
14 extraReducers: (b) =>
15 b.addCase(placeOrder.fulfilled, (s, a) => void (s.lastOrderId = a.payload.orderId))
16 .addCase(placeOrder.rejected, (s, a) => void (s.error = a.error.message ?? "Error")),
17});
18
19export function CheckoutButton({ cartId }: { cartId: string }) {
20 const dispatch = useDispatch<any>();
21
22 async function onClick() {
23 try {
24 const { orderId } = await dispatch(placeOrder(cartId)).unwrap(); // dispatching a thunk
25 alert(`Order ${orderId} placed`);
26 } catch (e) {
27 alert((e as Error).message);
28 }
29 }
30 return <button onClick={onClick}>Place order</button>;
31}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app