Blog>
Snippets

Creating typed hooks for Redux

Demonstrate how to create typed hooks like useAppDispatch and useAppSelector that leverage TypeScript to ensure type safety with Redux 5.0.0 state and dispatch.
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
This piece of code defines typed versions of the `useDispatch` and `useSelector` hooks using TypeScript. First, the needed functions and types from Redux are imported. The `useAppDispatch` hook is defined to dispatch actions with the correct type for the application. The `useAppSelector` hook is typed with the `RootState` type, ensuring that the selector functions will receive the correct state type.