I tried using useContext() in my react-app via vite but it gives an error "ReferenceError: AuthContext is not defined"
App.js is given below:
/*eslint-disable*/
import SomeComponent from './SomeComponent';
import './App.css';
const AuthContext = createContext(null);
function App() {
const [someValue, setSomeValue] = useState('whatever');
return (
<AuthContext.Provider value={{someValue}}>
<SomeComponent/>
</AuthContext.Provider>
);
}
export default App
SomeComponent.js is given below:
/*eslint-disable*/
import { useContext } from "react";
function SomeComponent() {
const {someValue} = useContext(AuthContext);
return (
<div>
whatever! this is {someValue}
</div>
)
}
export default SomeComponent
I ran npm run dev again but it doesn’t fix the issue. React-DevTools on Chrome even shows that context is being provided to SomeComponent but still I cannot consume the context via useContext() at all. What error am I making?
2
Answers
Ok, I solved the issue. I used Phil's technique but wrapped AuthContext.Provider around in another component which returned
You need to export
AuthContext
from wherever it’s defined and import it where you need itFor example
and
A convenient trick is to encapsulate the context within a custom hook in the same place where it’s defined.
For example, in
App.js
and in your components