Sometimes, we want to use React createContext in Typescript.
In this article, we’ll look at how to use React createContext in Typescript.
How to use React createContext in Typescript?
To use React createContext in Typescript, we need to define the types for the context props.
For instance, we write
import React, { useReducer } from "react";
import { initialState, IState, reducer } from "./reducer";
interface IContextProps {
state: IState;
dispatch: ({ type }: { type: string }) => void;
}
export const AdminStore = React.createContext({} as IContextProps);
export function AdminStoreProvider(props: any) {
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return (
<AdminStore.Provider value={value}>{props.children}</AdminStore.Provider>
);
}
to create the IContextProps
interface and use that as the type for the value
prop in AdminStore.Provider
by writing
export const AdminStore = React.createContext({} as IContextProps);
IState
is a type that we created to add types to the value
prop values.
Now the TypeScript compiler should use the types and type errors should clear.
Conclusion
To use React createContext in Typescript, we need to define the types for the context props.