I am trying to create a React Context
with TypeScript to share state between components. When creating the Context, I tried passing null
as the initial value.
// contexts.ts file
import { createContext } from 'react';
export const AuthorContext = createContext(null);
But when trying to pass the state value
and setter function
to the value of the Provider
this would cause problems because not assignable to type null.
const [message, setMessage] = useState<string>("");
<AuthorContext.Provider value={{ message, setMessage }}>
<Switch>
<Route path={`${path}/first`} component={FirstContextContainer} />
<Route path={`${path}/second`} component={SecondContextContainer} />
</Switch>
</AuthorContext.Provider>
So I tried creating an interface
with the type definitions the error message gave me.
interface IStateStringDef {
stateVal: string;
setStateVal: React.Dispatch<React.SetStateAction<string>>;
}
And update my Context
and Provider
.
// contexts.ts file
export const AuthorContext = createContext<IStateStringDef | null>(null);
// file where provider is
<AuthorContext.Provider value={{ stateVal: message, setStateVal: setMessage }}>
And this works but doesn't seem like the most correct and elegant way to do it, what is the correct way for creating and using a context in TypeScript?