How to Update Redux Dispatch in React
This article explains how to update state in a React application by
dispatching actions to a Redux store. You will learn how to import and
use the useDispatch hook from the react-redux
library, structure your action creators, and trigger state changes from
your React components.
In Redux, the state cannot be mutated directly. Instead, the only way to update the Redux state is to dispatch an action. An action is a plain JavaScript object that describes what happened, and the dispatch function sends this action to the Redux store’s reducer to trigger the state update.
To use dispatch in a modern React functional component, you use the
useDispatch hook provided by the react-redux
package.
Step 1: Import the Hook and Action Creators
First, import useDispatch from react-redux
and the specific action creators you defined in your Redux slice or
reducer file.
import { useDispatch } from 'react-redux';
import { updateUsername } from './userSlice'; Step 2: Initialize the Dispatch Function
Inside your functional component, call the useDispatch
hook to get access to the dispatch function.
const UserProfile = () => {
const dispatch = useDispatch();
// ...
};Step 3: Trigger the Dispatch on User Interaction
You can now call the dispatch function inside event
handlers, such as button clicks or form submissions. Pass your action
creator as an argument to dispatch, along with any payload
data needed to update the state.
const handleUpdate = () => {
const newName = "Jane Doe";
// Dispatching the action with a payload
dispatch(updateUsername(newName));
};
return (
<div>
<button onClick={handleUpdate}>Update Name</button>
</div>
);How the Flow Works
- User Interaction: The user clicks the button,
triggering the
handleUpdatefunction. - Dispatching: The
dispatchfunction sends theupdateUsername('Jane Doe')action object to the Redux store. - Reducer Processing: The store runs the reducer
function corresponding to that action, receives the payload
(
Jane Doe), and updates the state. - Component Re-rendering: Any React component
subscribed to this piece of state using the
useSelectorhook will automatically re-render with the updated data.