What does the useDispatch() hook do?
The useDispatch() hook is the second (and very important) hook from the React-Redux library,
and it exists so a React component can dispatch actions to the Redux store.
Definition
useDispatch()is a hook that returns thedispatch()function, which you use to send actions to the Redux store.
Signature
javascript
const dispatch = useDispatch()After that, dispatch can be used to call:
javascript
dispatch({ type: 'ACTION_TYPE', payload: data })Usage example
javascript
import { useSelector, useDispatch } from 'react-redux'
function Counter() {
const count = useSelector(state => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
)
}Here:
useDispatch()gives access tostore.dispatch- When you click the button → an action is dispatched
- The reducer processes it → a new state is created → React automatically re-renders the component
What happens under the hood
useDispatch()gets the Redux store itself from context (<Provider store={store}>).- It returns a reference to
store.dispatch. - When you call
dispatch(action):
- Redux passes the
actionto all reducers; - each reducer decides whether the state needs to change;
- if the state changed → React components using
useSelector()update.
You can dispatch more than just objects
If you have a middleware connected, for example redux-thunk or redux-saga,
then dispatch can accept not just objects, but also functions or generators:
Example with redux-thunk:
javascript
function fetchUser(id) {
return async (dispatch) => {
dispatch({ type: 'USER_FETCH_START' })
const data = await fetch(`/api/users/${id}`).then(r => r.json())
dispatch({ type: 'USER_FETCH_SUCCESS', payload: data })
}
}And in the component:
javascript
dispatch(fetchUser(5))Where to use it
- In event handlers (
onClick,onSubmit, etc.) - In effects (
useEffect), if you need to dispatch an action on mount - In callback functions memoized with
useCallback
The key idea
useSelector()reads data from ReduxuseDispatch()dispatches actions to change that data
They always work in pairs.
Summary
| Hook | What it does | Example |
|---|---|---|
useSelector() | Pulls data from Redux state | const count = useSelector(s => s.counter) |
useDispatch() | Dispatches an action to the store | dispatch({ type: 'INCREMENT' }) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.