create a react context in javascript

To create a React context, you can use the createContext() method provided by the React library. Here is an example of how to create a context and use it in your components:

// Define a context
const MyContext = React.createContext();

// Create a provider component that will provide the context to its children
function MyProvider({ children }) {
  const [state, setState] = useState(null);

  return (
    <MyContext.Provider value={[state, setState]}>
      {children}
    </MyContext.Provider>
  );
}

// Use the context in a child component using the consumer component
function MyComponent() {
  return (
    <MyContext.Consumer>
      {([state, setState]) => (
        <div>
          <p>State: {state}</p>
          <button onClick={() => setState("new state")}>Set State</button>
        </div>
      )}
    </MyContext.Consumer>
  );
}
673 chars
28 lines

In the example above, we create a context with createContext() and use it inside a MyProvider component. The provider receives a state value and a setState function in its value prop, which we pass as an array. Inside the MyComponent component, we access the state and setState function using the consumer component.

gistlibby LogSnag