Redux & Redux Toolkit — App-Wide State ManagementEntry 8 of 11
Typed Hooks
Pre-typed versions of useSelector and useDispatch that know the store's RootState and AppDispatch.
Notes
- Without them, every
useSelectorcall needs(state: RootState) => .... AppDispatchincludes thunk support, so dispatching async thunks (Entry 9) type-checks.- Define once, import everywhere instead of the plain hooks.
What / Why / When
- What
One-time typing for store hooks.
- Why
Less repetition, full autocomplete, fewer type errors.
- When
Every TypeScript RTK project.
Code compare
// store/hooks.tsimport { useDispatch, useSelector } from "react-redux";import type { AppDispatch, RootState } from "./index";export const useAppDispatch = useDispatch.withTypes<AppDispatch>();export const useAppSelector = useSelector.withTypes<RootState>();// components/Header.tsximport { useAppDispatch, useAppSelector } from "../store/hooks";import { authActions } from "../store/auth-slice";export default function Header() { const dispatch = useAppDispatch(); const isAuth = useAppSelector((state) => state.auth.isAuthenticated); // typed return ( <header> {isAuth && <button onClick={() => dispatch(authActions.logout())}>Logout</button>} </header> );}Not needed. createFeature selectors are already typed, and inject(Store) dispatches typed action creators.
No Angular code for this example.
Quick reference
| React | Angular |
|---|---|
useAppSelector, useAppDispatch | Typed selectors from createFeature |