Redux & Redux Toolkit
/Beginner
useDispatch()
Definition
A React hook that returns a reference to the `dispatch` function from the Redux store. You use it to dispatch actions as needed.
Explain Like I'm New
The 'Writer'. If `useSelector` is how you read the data, `useDispatch` is how you change the data. You grab the dispatch function, and throw an action at it when a user clicks a button.
Real World Example
A 'Dark Mode' toggle switch. When the user clicks the switch, it calls `dispatch(toggleTheme())`.
Common Use Cases
- •Triggering state mutations from UI events
Interactive Example
import { useDispatch, useSelector } from 'react-redux'; // Import the action creator from our slice! import { increment, decrement } from './counterSlice'; function Counter() { const count = useSelector((state) => state.counter.value); const dispatch = useDispatch(); return ( <div> <span>{count}</span> {/* Dispatch the action when the button is clicked */} <button onClick={() => dispatch(increment())}>+</button> <button onClick={() => dispatch(decrement())}>-</button> </div> ); }
Interview Questions
basic
- Do you need to pass the Redux `store` into `useDispatch()`?
intermediate
- Does the `dispatch` function reference change on every re-render?