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' })- We call
dispatch()and pass anactionobject ({ type: 'INCREMENT' }). - Redux sends this action to all the reducers.
- The reducer(s) return the new state.
- Redux updates the store (
store). - 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 1In 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:
dispatch()sends the action{ type: 'INCREMENT' }- the
reducerreceives that action - it returns the new state
{ count: 1 } - React updates the component with the new value
Summary
What dispatch() does | Analogy |
|---|---|
| Sends an action to the reducer | Like "telling the system" that the user did something |
| Starts the state update process | Like "raising an event" |
| Does not change the state directly | It only "asks" the reducer to change it |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.