skip to Main Content

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


  1. Chosen as BEST ANSWER

    Ok, I solved the issue. I used Phil's technique but wrapped AuthContext.Provider around in another component which returned


  2. You need to export AuthContext from wherever it’s defined and import it where you need it

    For example

    export {
      App as default,
      AuthContext,
    };
    

    and

    import { AuthContext } from "./path/to/App";
    

    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

    const useAuth = () => useContext(AuthContext);
    
    export {
      App as default,
      useAuth,
    };
    

    and in your components

    import { useAuth } from "./path/to/App";
    
    function SomeComponent() {
    
      const { someValue } = useAuth();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search