Blog>
Snippets

Implementing Typed Hooks with TypeScript

Show how to use `useSelector` and `useDispatch` typed hooks in TypeScript to work with the updated Redux v5.0.0.
import { useSelector, TypedUseSelectorHook, useDispatch } from 'react-redux';
import type { RootState, AppDispatch } from './store';

// Use throughout your app instead of plain `useSelector` and `useDispatch`
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
export const useAppDispatch = () => useDispatch<AppDispatch>();
This snippet defines typed versions of 'useSelector' and 'useDispatch'. 'useAppSelector' and 'useAppDispatch' are custom hooks that will be used throughout the application to access the state and dispatch actions with types specific to the application's store.
import { useAppSelector, useAppDispatch } from './hooks';

// In your component
const MyComponent: React.FC = () => {
  // Typed selector for state
  const myStateValue = useAppSelector(state => state.myState);
  // Typed dispatch function
  const dispatch = useAppDispatch();

  // Use dispatch function to dispatch actions
  const handleAction = () => {
    dispatch({ type: 'MY_ACTION', payload: /* payload here */ });
  };

  // Component rendering and other logic

  return (
    <div>
      {/* Your component JSX */}
    </div>
  );
};
This snippet demonstrates how to use the typed hooks 'useAppSelector' and 'useAppDispatch' within a React component. 'myStateValue' is a piece of state retrieved through 'useAppSelector', and 'dispatch' is used to dispatch actions to the Redux store.