
what is UseSelectore Hook and UseDispatch Hook
useSelector and useDispatch are custom React Hooks provided by the react-redux library, designed to simplify interaction with a Redux store within React functional components. They offer a modern alternative to the traditional connect Higher-Order Component.
1. useSelector Hook
What it does:
It reads data from the Redux store.
Syntax:
const data = useSelector((state) => state.sliceName.property);
Example:
const count = useSelector((state) => state.counter.value);
- state is the entire Redux store
- You extract a piece of state to use in the component
2. useDispatch Hook
What it does:
It dispatches an action to the Redux store (to update the state).
Syntax:
const dispatch = useDispatch();
dispatch(actionFunction());
Example:
const dispatch = useDispatch();
dispatch(increment()); // calling a Redux action
Full Example Together
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './features/counter/counterSlice';
const Counter = () => {
const count = useSelector((state) => state.counter.value); // Read from store
const dispatch = useDispatch(); // Create dispatch function
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
};
Summary Table
Hook | Purpose | Usage |
---|---|---|
useSelector | Read data from Redux store | useSelector((state) => state.auth.user) |
useDispatch | Send actions to Redux reducer | dispatch(addUser(payload)) |
Bonus Tip:
- useSelector automatically subscribes to store updates
- useDispatch is used to trigger state changes via actions
Comments
Add new comment