Application-wide selector hook
Centralize Redux typing for React components.
Redux Toolkit · Type Alias
TypedUseSelectorHook is a React-Redux type for creating an application-specific, pre-typed useSelector hook. Supplying RootState gives selectors the store-state type and avoids repeating state annotations.
TypedUseSelectorHook is a generic type used to declare an application-specific useSelector hook. Parameterizing it with RootState makes selectors receive the complete store state type and lets TypeScript infer each selector's result.
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector| Name | Type | Description |
|---|---|---|
State | RootState | The complete Redux store state type used to type selector input. |
A typed useSelector hook whose selector result is inferred from the selector function.
import { configureStore } from '@reduxjs/toolkit'
import { TypedUseSelectorHook, useSelector } from 'react-redux'
import type { RootState } from './store'
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
export function Counter() {
const count = useAppSelector((state) => state.counter.value)
return <span>{count}</span>
}The application-specific hook automatically supplies RootState to selectors.
Centralize Redux typing for React components.
Avoid annotating selector state in every component.
Keep store and hook declarations modular.
TypedUseSelectorHook<RootState> describes a useSelector hook whose selector receives RootState. Assigning useSelector to that type creates a reusable, application-specific hook that avoids repeating the state annotation.
Follow-up: How can the selector's result type be inferred? The selector receives the typed state, so TypeScript infers its returned value and uses that as the hook result type.
Declare a hook such as useAppSelector: TypedUseSelectorHook<RootState> = useSelector. Components then call useAppSelector and do not need to annotate (state: RootState) in every selector.
Follow-up: Where should this declaration live? Put it in a separate hooks file, because the declarations are runtime variables and separating them can avoid circular dependencies.
The generic argument is the type of the entire Redux store state, commonly RootState. The selector is called with that state, and its selected return value becomes the hook's return value.
Follow-up: What should a selector return? It should return the specific data needed by the component, either directly from state or as derived data.
useSelectoruseDispatchRootStateAppDispatch