Skip to content

Instantly share code, notes, and snippets.

@manduks
Created September 16, 2020 19:56
Show Gist options
  • Save manduks/e33cc909b61a87d6970d8f6268e7098f to your computer and use it in GitHub Desktop.
Save manduks/e33cc909b61a87d6970d8f6268e7098f to your computer and use it in GitHub Desktop.
Context example
const CounterContext = React.createContext();
function useCount() {
const context = React.useContext(CounterContext)
if (!context) {
throw new Error(`useCount must be used within a CountProvider`)
}
return context;
}
function CounterProvider(props) {
const [count, setCount] = React.useState(props.value || 0);
const value = React.useMemo(() => [count, setCount], [count]);
return <CounterContext.Provider {...props} value={value} />
}
function Counter() {
const [counter, setCounter] = useCount();
return (
<button onClick={()=> setCounter(c => c + 1)}>
Button {counter}
</button>
);
}
function Display() {
const [counter] = useCount();
return (
<div>{counter}</div>
);
}
function App() {
return (
<div style={{display: 'flex', flexDirection: 'column', width: 400, alignItems: 'center'}}>
<CounterProvider value={0}>
<Counter/>
<Display/>
</CounterProvider>
<div>--------------</div>
<CounterProvider value={9}>
<Counter/>
<Counter/>
</CounterProvider>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment