One of advantages of using typescript are that it reduces the risk of Bugged Code and more Information/Documentation in Your Codebase. In order to fully embrace these cool features in our react application when using redux we have to use typed react-redux hooks. In this article we are going to explore how we can perform typing on useSelector
hook.
When using typed useSelector hook our editor is able to detect properties that are associated with our redux central state.
In order to achieve this we have create a custom hook let's name is useTypedSelector
. But before we jump in and implement this cool hook we have to first make some adjustment.
Before we create this hook we have to first determine the type of our redux state i.e properties of the central state. To achieve this we have to perform the following step:
// import all reducers
import {combineReducers, createStore, applyMiddleware} from "redux";
// combine reducers
const reducer = combineReducers({});
export const store =createStore(reducer);
export type RootState = ReturnType<typeof reducer>;
In order to annotate typed useSelector hook we need RootState which represent the type of our redux central state.
So in order to implement our custom typed useSelector hook we need TypedUseSelectorHook
interface from react-redux
and our RootState
for annotation.
import {useSelector, TypedUseSelectorHook} from "react-redux";
import {RootState} from "../state";
export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;
After this, then we can go on and use this hook to select slices of our state we need to use.
Top comments (0)