I have a super simple React Typescript project using the Context API to pass down a useState hook.
export const AppContext = React.createContext(null);
function App() {
const [value, setValue] = React.useState(3);
return (
<AppContext.Provider
value={{
value,
setValue
}}
>
<div>
<h1>App</h1>
<Child />
</div>
</AppContext.Provider>
);
}
It's working fine on Code Sandbox: https://codesandbox.io/s/interesting-lamarr-fyy1b
However when I create a project with Create React App (npx create-react-app project-name --typescript
) and try the same code I get an error:
Type '{ value: number; setValue: Dispatch>; }' is not assignable to type 'null'. TS2322
I think this is happening as null
is the initial value for AppContext
but is then overridden by the value
passed to the Provider
?
If this is the case how can I fix it? I assume one way it so relax the TypeScript settings? However is there a more elegant way of writing the code which avoids this problem? I'm new to TypeScript and the Context API so not sure if I'm doing one or both in an inadvisable way.