liveBook · Manning

Dispatch

As explained in React Hooks in Action: With Suspense and Concurrent Mode

A dispatch function is the function returned by useReducer that sends an action to the reducer for state transition.

A dispatch function is returned by useReducer alongside the current state. Call it with an action when an event occurs; React passes that action and the current state to the reducer, then uses the returned state for the next render. section 3.2.3 section 3.4

Use dispatch to:

  • Replace separate state updates with named actions when several state values are interrelated. section 3.5
  • Send ordinary JavaScript objects such as { type: "SET_NAME", payload: "Jamal" } to a reducer. section 3.5
  • Pass state and dispatch to child components through props when a parent owns the reducer. section 6.3.3 section 6.6
  • Include dispatch in an effect dependency array when it arrives as a prop. section 6.3.3

Toggling details in BookablesList

Initialize the reducer with const [state, dispatch] = useReducer(reducer, initialState). A checkbox can dispatch({ type: "TOGGLE_HAS_DETAILS" }); the reducer handles the action, returns updated state, and React calls the component again with the latest state. section 3.2.3

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

The compact useReducer pattern shows dispatch paired with state and a reducer. section 3.2.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains action dispatch, reducer transitions, initialization, rerendering, stable identity, and dependency-array treatment.
Examples
Uses BookablesList controls, a details checkbox, and asynchronous bookable-data requests as dispatch examples.
What it assumes
Assumes familiarity with React components, hooks, event handlers, reducers, actions, state, and props.
What you can do after
Apply it via React useReducer to trigger named state transitions from handlers, effects, and child components.
How it connects
Connects dispatch with useReducer, reducers, actions, state, props, useEffect, and useCallback.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.