Skip to content

Instantly share code, notes, and snippets.

@penx
Created March 12, 2020 12:11
Show Gist options
  • Save penx/47d7b8f3dc808a05e1f5bd36940140b1 to your computer and use it in GitHub Desktop.
Save penx/47d7b8f3dc808a05e1f5bd36940140b1 to your computer and use it in GitHub Desktop.
import React, { useState, createContext, useContext } from "react";
const SetContext = createContext();
const ValueContext = createContext();
const SetProvider = React.memo(({ set, ...props }) => (
<SetContext.Provider value={set} {...props} />
));
const Provider = props => {
const [value, set] = useState("initial");
return (
<ValueContext.Provider value={value}>
<SetProvider set={set} {...props} />
</ValueContext.Provider>
);
};
const Value = () => {
const value = useContext(ValueContext);
return <div>{value}</div>;
};
const SetValue = () => {
const set = useContext(SetContext);
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