Redux & Redux Toolkit Course
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`?

Flash Cards

Question

Which two?

Click to reveal answer
Answer

`useDispatch` and `useSelector`.

Question

Why type dispatch?

Click to reveal answer
Answer

If you are using Redux Thunk (async actions), the default `Dispatch` type doesn't know how to handle Thunks. `AppDispatch` fixes this, enabling autocomplete for your async actions.