I am trying to use React contexts to manage my states throughout child components in typescript. However, I currently face an issue with the following code:
Inside contexts/context.ts I have:
export const MyContext = React.createContext(null);
Inside components/Parent.tsx I have:
import {MyContext} from '../contexts/context';
export default function Parent() {
const [state, setState] = React.useState([]);
const MyContextManager = React.useContext(MyContext);
return (
<MyContextManager.Provider value={[state, setState]}>
<Child />
</MyContextManager.Provider>
)
}
And inside my Child component I have:
const [state, setState] = React.useContext(MyContext);
const handleState = (value) => {
setState(value);
}
However, I currently get an error:
TypeError: MyContextManager is null
You meant to use MyContext.Provider. Check the documentation.
Also you mentioned using TypeScript, yet that TypeError is a runtime error. It seems like TS thinks your MyContextManager is of type any or so. That, or TypeScript thinks having null as a component type is fine.