Using react context with react hooks in typescript
While creating Context, you are providing an initial value to it. Provide it in the same format as you expect it to be for the Provider like:
const initialState = {
authState : {
email: '',
password: ''
},
authActions = {
setEmail: () => {},
setPassword: () => {}
};
};
const AuthCtx = createContext(initialState);
Also, you don't even need the initialState since its only passed to Consumer, if you don't have a Provider higher up in the hierarchy for the Consumer.
Answer above works, because strict rules of checking of types disabled. Example for context with strict rules:
import { createContext, Dispatch, SetStateAction, useState } from 'react';
import { Theme } from '@styles/enums';
import { Language } from '@common/enums';
type Props = {
children: React.ReactNode;
};
type Context = {
appLang: string;
appTheme: string;
setContext: Dispatch<SetStateAction<Context>>;
};
const initialContext: Context = {
appLang: Language.EN,
appTheme: Theme.DEFAULT,
setContext: (): void => {
throw new Error('setContext function must be overridden');
},
};
const AppContext = createContext<Context>(initialContext);
const AppContextProvider = ({ children }: Props): JSX.Element => {
const [contextState, setContext] = useState<Context>(initialContext);
return (
<AppContext.Provider value={{ ...contextState, setContext }}>
{children}
</AppContext.Provider>
);
};
export { AppContext, AppContextProvider };
It works for me. Theme
and Language
it just enums, like this:
export enum Theme {
DEFAULT = 'DEFAULT',
BLACK = 'BLACK',
}
And I send Error function in setContext
inner initialContext
for throwing error if programmer doesn't define setContext
in Provider
. You can just use
setContext: (): void => {}
Good luck!