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

thing i have tried

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();