Search code examples
reactjsreact-context

Why my useContext is not working in my code


I have just started learning useContext hook and I am struck in this problem.

I am not able use the hook itself when I am trying to print that in console its says undefined.

This is the App.js

import "./styles.css";
import NoteState from "./Context/Notes/NoteState";
import About from "./components/About";
export default function App() {
  return (
    <>
      <About />
      <div>ankit</div>
      <NoteState>
        <About />
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      </NoteState>
    </>
  );
}

These are the files where the hook is defined

    import { createContext } from "react";
    
    const noteContext = createContext();
    
    export default noteContext;


Second one is  

import React from "react";
import NoteContext from "./NoteContext";

const NoteState = (props) => {
  const state = {
    name: "Name",
    surname: "Surname"
  };
  return (
    <>
      <NoteContext.Provider value={state}>
        {props.childern}
      </NoteContext.Provider>
    </>
  );
};

export default NoteState;

I am trying to use this in About.jsx

import React from "react";
import noteContext from "../Context/Notes/NoteContext";
import { useContext } from "react";
const About = () => {

  const a = useContext(noteContext);

  console.log(a); - >> comes undefined
  return (
    <>
      {/* <div>this is about note me but {a.name}</div> */} this gives error
    </>
  );
};
export default About;

You can see the same in this codesand box link. link


Solution

  • There seems to be a typo in your NoteState component. It should be props.children and not childern. When I made that change and ran your sandbox, it was working fine.