Blog>
Snippets

Typed Hooks for Redux

Demonstrate the use of TypeScript to create typed versions of the `useSelector` and `useDispatch` hooks, ensuring correct type inference within components.
// hooks.ts
import { TypedUseSelectorHook, useSelector as rawUseSelector, useDispatch as rawUseDispatch } from 'react-redux';
import { RootState, AppDispatch } from './store';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => rawUseDispatch<AppDispatch>(); // Typed dispatch hook
export const useAppSelector: TypedUseSelectorHook<RootState> = rawUseSelector; // Typed selector hook
This piece of code defines typed versions of Redux hooks by using TypeScript generics. The useAppDispatch hook is typed with the AppDispatch type, which should correspond to the dispatch type in the Redux store. The useAppSelector hook is typed with the RootState type representing the state structure.
// store.ts
import { configureStore } from '@reduxjs/toolkit';

export const store = configureStore({
  reducer: {
    // Reducers go here
  },
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
This code snippet demonstrates the creation of a Redux store using Redux Toolkit's configureStore function. Additionally, it exports RootState and AppDispatch types derived from the store, which will be used to type useSelector and useDispatch hooks.
// Component.tsx
import React from 'react';
import { useAppSelector, useAppDispatch } from './hooks';

const MyComponent: React.FC = () => {
  const dispatch = useAppDispatch(); // Now returns the typed `AppDispatch` function
  const myValue = useAppSelector(state => state.myReducer.value); // `state` is typed with `RootState`

  // Use dispatch and useSelector as you normally would but with type safety
  return <div>{myValue}</div>;
};

export default MyComponent;
This component demonstrates how to use the typed hooks within a React functional component. By using useAppSelector, we can select a value from the state with the assurance that `state` is correctly typed. With useAppDispatch, when we dispatch actions, the dispatch function is typed with AppDispatch.