I have a parent component that can use useContext()
to return the context, but if it's child component uses useContext()
it returns the initial context (null in this case) and not the actual context.
I have no idea why this is happening because the parent component is wrapped in the provider, so the child must also have access to it.
Here's the code:
ApolloContext.js
import { createContext } from 'react';
export const ApolloContext = createContext(null);
index.js
<ApolloProvider client={client} store={store}>
<Router>
<ApolloContext.Provider value={client}>
<App scopes={scopes} userId={userId} />
</ApolloContext.Provider>
</Router>
</ApolloProvider>,
Parent component:
import { ApolloContext } from "../context/apollo/ApolloContext";
const ParentComponent = () => {
console.log(useContext(ApolloContext)) // <- returns client
...
return (
<Child />
)
}
Child component
import { ApolloContext } from "../context/apollo/ApolloContext";
const Child = () => {
console.log(useContext(ApolloContext)) // <- returns null
...
return (
<div> hello </div>
)};