How to use useContext?

Here is my code:


I have search tag process in CreateTag.js .

And I fetched the API data in the Students.js component while the Student.js component is in the Students.js

And the tag I made is inside the State that exists in CreateTag.js .

And the CreateTag.js is inside the Student.js component.

The tree components are: Students.js => Student.js => CreateTag.js


Hi i found a guide onto how to useContext that helps explaining how it works and how to use

You’re missing the component where you store the context.

import React from "react";

export const UserContext = React.createContext(null);

export const UserProvider = (props) => {
  // What are you storing????
  // What are you using to update it????
  // I assume the fetch logic to get lists of students???
  const [foo, setFoo] = React.useState("whatever");

  return (
    <UserContext.Provider value={{ foo, setFoo }}>
      { props.children }
    </UserContext.Provider>
  );
};

Then in your entry point (eg App.js):

//......
import { UserProvider } = from "./user-context";
// ......

export const App = () => (
  <UserProvider>
    // rest of app
  </UserProvider>
);

Then in the components you want to use it in:

//......
import { UserContext } = from "./user-context";
// .......

export const FooComponent = () => {
  const { foo, setFoo } = React.useContext(UserContext);

  return (
    <>
      <p>Foo is currently "{foo}"</p>
      <button onClick={() => setFoo("changed it!")}>Change foo value</button>
    </>
  );
};