How to Implement Redux Dispatch in React
In this guide, you will learn how to implement Redux Dispatch in a
React application to update your global state. We will cover the
essential steps to set up the useDispatch hook from the
react-redux library, define actions, and trigger state
changes through user interactions using a straightforward, practical
code example.
Understanding Redux Dispatch
In Redux, the state is read-only. The only way to modify the state is
by dispatching an “action.” An action is a plain JavaScript object that
describes an event or update. The Redux store receives this action and
passes it to a reducer, which then calculates and returns the new state.
In React, the useDispatch hook is the standard way to send
these actions to your Redux store from within functional components.
Step 1: Install the Required Packages
To use Redux in your React project, make sure you have installed
@reduxjs/toolkit and react-redux.
npm install @reduxjs/toolkit react-reduxStep 2: Create a Slice and Actions
Using Redux Toolkit, you can define your state and reducers inside a “slice.” The slice automatically generates action creators for you. Here is an example of a simple counter slice:
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
}
}
});
// Export the auto-generated action creators
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;Step 3: Configure the Redux Store
You need to provide the store to your React application using the
Provider component.
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});Wrap your main application component with the Provider
in your entry file (usually main.js or
index.js):
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider store={store}>
<App />
</Provider>
);Step 4: Use
useDispatch in a React Component
To dispatch actions, import the useDispatch hook from
react-redux along with your action creators. Call
useDispatch() inside your component to get the dispatch
function, then invoke it inside your event handlers.
// CounterComponent.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement, incrementByAmount } from './counterSlice';
function CounterComponent() {
// Initialize the dispatch function
const dispatch = useDispatch();
// Access the current count value from the store
const count = useSelector((state) => state.counter.value);
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h2>Count: {count}</h2>
{/* Dispatch actions on button clicks */}
<button onClick={() => dispatch(increment())}>
Increment
</button>
<button onClick={() => dispatch(decrement())} style={{ margin: '0 10px' }}>
Decrement
</button>
<button onClick={() => dispatch(incrementByAmount(5))}>
Add 5
</button>
</div>
);
}
export default CounterComponent;Key Summary
- Import
useDispatch: Pull the hook fromreact-redux. - Retrieve the dispatch function: Call
const dispatch = useDispatch()inside your functional component. - Dispatch actions: Call
dispatch(actionCreator())inside your event listeners (likeonClick) to send the update to the store.