Skip to content

Instantly share code, notes, and snippets.

@penx
Created March 12, 2020 12:05
Show Gist options
  • Save penx/d7fa03a7b3af970dba5253513f98b8f2 to your computer and use it in GitHub Desktop.
Save penx/d7fa03a7b3af970dba5253513f98b8f2 to your computer and use it in GitHub Desktop.
import React, { useState, createContext, useContext } from "react";
const MyContext = createContext();
const Provider = props => {
const [value, set] = useState("initial");
return <MyContext.Provider value={{ value, set }} {...props} />;
};
const Value = () => {
const { value } = useContext(MyContext);
return <div>{value}</div>;
};
const SetValue = () => {
const { set } = useContext(MyContext);
return <button onClick={() => set(Date.now())}>Change</button>;
};
export default function App() {
return (
<Provider>
<Value />
<SetValue />
</Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment