Search code examples
javascriptreactjstypescriptuse-context

getting problem on using useContext in react?


I have a simple react app in which i have to use useContext.

(btw im using vite + react)

here is my code for Context.jsx

import React, {useContext} from 'react';

const emailContext = React.createContext();

export const useEmail = () => useContext(emailContext);

export const emailProvider = ({children}) => {
  const currentUser = "None";

  const value = {
    currentUser
  }

  return(
    <emailContext.Provider value={value}>
      {children}
      </emailContext.Provider>
  )
}

and heres how i am using the context

import "./styles.css";
import { useEmail } from "./Context/Context"

export default function App() {

  const {currentUser} = useEmail();

  return (
    <div className="App">
      <h1>Hello CodeSandbox {currentUser}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I am sure why I am getting error in this code.

some of the errors that I am getting

  • _useEmail is undefined (latest)
  • currentUser user is undefined

thing i have tried

  • Initialized createContext with some initial value (only intial value is visible).
  • using useContext() directy in the App.js (useContext(emailContext) return undefined)
  • instead of {children} used <children/>.
  • used useState instead of const currentUser in emailProvider

I am getting same problem even when I use typescript.

but none of the above helped.


Solution

  • You should wrapping app with <emailProvider></emailProvider> to using data in value={value}. Now it gets undefined from const emailContext = React.createContext();