Currently, I am working on a React Typescript project that utilizes 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>
);
}
The project is functioning correctly on Code Sandbox: https://codesandbox.io/s/interesting-lamarr-fyy1b
However, upon attempting to replicate the setup in a project created with Create React App (
npx create-react-app project-name --typescript
), I encountered an error:
Type '{ value: number; setValue: Dispatch>; }' is not assignable to type 'null'. TS2322
I suspect that this issue arises because null
is initially set as the value for AppContext
, but it gets overridden by the value
passed to the Provider
.
If my assumption is correct, what would be the best way to address this problem? Could relaxing the TypeScript settings be a solution, or is there a more elegant workaround that avoids this conflict altogether? As someone new to both TypeScript and the Context API, I'm unsure if my approach is less than ideal in either aspect.