Learn the concept
State Management
useSelector reads data from the Redux store by accepting a selector function that receives the entire state and returns the needed slice. useDispatch returns the store's dispatch function to send actions. Together they replace the older connect() HOC pattern with a simpler hooks-based API.
React-Redux hooks provide a direct way to interact with the Redux store from functional components:
useSelector(selectorFn, equalityFn?)
(state) => state.someSliceshallowEqual or memoized selectors (Reselect)useDispatch()
dispatch functiondispatch(actionCreator())vs connect() HOC: | Feature | Hooks | connect() | |---------|-------|-----------| | Syntax | Direct in component | Wraps component | | Memoization | Manual (useMemo) | Built-in (shallow compare) | | TypeScript | Better inference | Complex typing | | Testing | Needs Provider | Can test mapState separately |
import { useSelector, useDispatch } from 'react-redux';
import type { RootState } from '../store';
import { increment, decrement } from '../features/counterSlice';
function Counter() {
// Read from store
const count = useSelector((state: RootState) => state.counter.value);
const userName = useSelector((state: RootState) => state.user.name);
// Get dispatch function
const dispatch = useDispatch();
return (
<div>
<p>{userName}'s count: {count}</p>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
}Using useSelector/useDispatch for centralized state in enterprise applications with many developers
Dispatching actions and using selectors to immediately reflect changes while syncing with server
Leveraging Redux DevTools to replay actions and inspect state changes during debugging
Build a full shopping cart with product listing, cart management, and checkout using Redux Toolkit
Implement a notification system with Redux middleware for WebSocket message handling