Redux & Redux Toolkit
/Intermediate
Typed Hooks (TypeScript)
Definition
Creating pre-typed versions of `useDispatch` and `useSelector` in TypeScript to avoid having to manually type `(state: RootState)` every time you select data.
Explain Like I'm New
In TypeScript, `useSelector((state) => state.auth)` will throw an error because TS doesn't know what `state` looks like. You create a custom `useAppSelector` hook once, tell it what your state looks like, and use that custom hook everywhere in your app instead.
Real World Example
Creating an `hooks.ts` file in your Redux folder that exports `useAppDispatch` and `useAppSelector`, and mandating that developers use those instead of the default React-Redux hooks.
Common Use Cases
- •TypeScript integration
- •Developer experience
Interactive Example
// app/hooks.ts import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; import type { RootState, AppDispatch } from './store'; // Use these EVERYWHERE in your app instead of plain `useDispatch` and `useSelector` export const useAppDispatch: () => AppDispatch = useDispatch; export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector; // -------------------------------------------------------- // In your components: import { useAppSelector } from '../app/hooks'; function MyComponent() { // Hover over 'state'. TypeScript magically knows exactly what it contains! const user = useAppSelector((state) => state.user); }
Interview Questions
basic
- Which two hooks do you usually recreate for TypeScript?
intermediate
- Why do you need a typed version of `useDispatch`?