Every time I want to use useSelector
I have to do something like this:
const isLoading = useSelector(
(state: RootStateOrAny) => state.utils.isLoading
);
Is there a way to disable needing to type out RootStateOrAny
every time? It's getting annoying.
CodePudding user response:
Yes. First, you should not be using the RootStateOrAny
type - that's an internal type from React-Redux. Instead you should be using your own app's RootState
type.
Second, you should specifically follow our recommended Redux TypeScript setup guidelines, and create a "pre-typed" version of the useSelector
hook, like:
// hooks.ts
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
and then use those pre-typed hooks everywhere.