Skip to main content

What does dispatch() do?

In Redux (and in useReducer in React), the dispatch() function is used to send an action - that is, to tell the system that an event happened and the state needs to be updated.


In simple words

dispatch() is a "courier" that delivers an action (a description of an event) to the reducer, and the reducer then decides how to change the state.


Example in Redux

javascript
store.dispatch({ type: 'INCREMENT' })
  1. We call dispatch() and pass an action object ({ type: 'INCREMENT' }).
  2. Redux sends this action to all the reducers.
  3. The reducer(s) return the new state.
  4. Redux updates the store (store).
  5. Subscribed components receive the updated state -> a render happens with the new data.

A full cycle example

javascript
// Reducer function counterReducer(state = { count: 0 }, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } default: return state } }
javascript
// Dispatching store.dispatch({ type: 'INCREMENT' }) // state.count is now 1

In React (useReducer)

The same thing, just local to the component:

javascript
function Counter() { const [state, dispatch] = useReducer(counterReducer, { count: 0 }) return ( <> <p>{state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}> + </button> <button onClick={() => dispatch({ type: 'DECREMENT' })}> - </button> </> ) }

When you click the button:

  1. dispatch() sends the action { type: 'INCREMENT' }
  2. the reducer receives that action
  3. it returns the new state { count: 1 }
  4. React updates the component with the new value

Summary

What dispatch() doesAnalogy
Sends an action to the reducerLike "telling the system" that the user did something
Starts the state update processLike "raising an event"
Does not change the state directlyIt only "asks" the reducer to change it

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.