Using useSelector and useDispatch
Learn how React components read Redux state using useSelector() and update state using useDispatch().
1. Introduction
React-Redux provides hooks that allow React components to work with the Redux store. Two of the most important hooks are useSelector() and useDispatch().
useSelector()
Reads the required data from the Redux store.
const count = useSelector(
(state) => state.counter.value
);
useDispatch()
Provides the dispatch function used to send actions to the Redux store.
const dispatch = useDispatch();
dispatch(increment());
2. Understanding useSelector()
useSelector() is a React-Redux hook that allows a component to select a value from the Redux store. When the selected result changes, React-Redux can trigger a re-render of the component.
Example Store Structure
{
counter: {
value: 10
}
}
Reading the Counter Value
import { useSelector } from "react-redux";
function CounterValue() {
const count = useSelector(
(state) => state.counter.value
);
return (
<h2>Counter Value: {count}</h2>
);
}
export default CounterValue;
Explanation
3. Selecting Data from Multiple Slices
A component can select data from different slices of the same Redux store. Consider an institute dashboard with student and course counts.
Example Store Structure
{
students: {
total: 25
},
courses: {
total: 8
}
}
Component Code
import { useSelector } from "react-redux";
function InstituteDashboard() {
const studentCount = useSelector(
(state) => state.students.total
);
const courseCount = useSelector(
(state) => state.courses.total
);
return (
<div>
<h2>Students: {studentCount}</h2>
<h2>Courses: {courseCount}</h2>
</div>
);
}
export default InstituteDashboard;
Expected Output
4. Understanding useDispatch()
useDispatch() returns the Redux store's dispatch function. Components use this function to send actions to the store. The corresponding reducer processes the action and calculates the next state.
Example
import { useDispatch } from "react-redux";
import { increment } from "./counterSlice";
function IncrementButton() {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch(increment())}>
Increment
</button>
);
}
export default IncrementButton;
How It Works
5. Create a Counter Slice
Before using useSelector() and useDispatch(), create a slice that defines the initial state and the actions that can update it.
File: 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;
},
reset: (state) => {
state.value = 0;
}
}
});
export const {
increment,
decrement,
reset
} = counterSlice.actions;
export default counterSlice.reducer;
createSlice() automatically generates the increment, decrement, and reset action creators from the reducer definitions.
6. Configure the Redux Store
File: store.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";
export const store = configureStore({
reducer: {
counter: counterReducer
}
});
The counter reducer is registered under the counter key. Therefore, the counter value can be accessed using state.counter.value.
7. Complete Counter Component
Now combine useSelector() and useDispatch() to read and update the counter value.
File: Counter.jsx
import {
useSelector,
useDispatch
} from "react-redux";
import {
increment,
decrement,
reset
} from "./counterSlice";
function Counter() {
const count = useSelector(
(state) => state.counter.value
);
const dispatch = useDispatch();
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => dispatch(increment())}>
Increment
</button>
<button onClick={() => dispatch(decrement())}>
Decrement
</button>
<button onClick={() => dispatch(reset())}>
Reset
</button>
</div>
);
}
export default Counter;
8. Provide the Store to React
Wrap the application with Provider so that Counter can access the Redux store.
File: main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import Counter from "./Counter";
createRoot(document.getElementById("root")).render(
<StrictMode>
<Provider store={store}>
<Counter />
</Provider>
</StrictMode>
);
9. Expected Counter Behavior
Increment | Decrement | Reset
These values show the expected behavior of the running React application. The preview above is illustrative; the actual buttons are implemented in Counter.jsx.
10. Common Mistakes
Incorrect State Path
Using state.value when the store actually contains state.counter.value causes the selector to read the wrong path.
Missing Provider
Components using React-Redux hooks must be rendered within a matching Provider that supplies the store.
Forgetting to Dispatch
Calling an action creator alone does not update the store. Dispatch the generated action using dispatch(actionCreator()).
Wrong Import Path
Verify the paths for counterSlice.js and store.js based on the folders in your project.
11. Practice Tasks
Task 1: Counter Application
Create a counter using useSelector() and useDispatch() with increment, decrement, and reset actions.
Task 2: Student Count
Create a students slice and display the total student count using useSelector().
Task 3: Add Student Button
Create an Add Student button that dispatches an action to increase the student count.
Task 4: Multiple Selectors
Create a dashboard that displays student and course totals from two different slices.
Summary
useSelector() reads selected values from the Redux store, while useDispatch() provides the function used to dispatch actions. When an action is dispatched, the corresponding reducer calculates the next state, and components subscribed to relevant state can update their UI. By combining createSlice(), configureStore(), Provider, useSelector(), and useDispatch(), React applications can manage shared state in a structured way. In the next lesson, we will learn how to handle asynchronous operations with Redux Toolkit.