Created
September 16, 2020 19:56
-
-
Save manduks/e33cc909b61a87d6970d8f6268e7098f to your computer and use it in GitHub Desktop.
Context example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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