const defaultValue = 0
const counterContext = React.createContext(defaultValue)
// Provider is a context's component that accepts value as a prop
const CounterProvider = counterContext.Provider
function App() {
const [counter, setCounter] = React.useState(0)
const handleIncrement = () => {
setCounter(prev => prev + 1)
}
const handleDecrement = () => {
setCounter(prev => prev - 1)
}
return (
<CounterProvider value={counter}>
<button onClick={handleIncrement}>
Increment
</button>
<button onClick={handleDecrement}>
Decrement
</button>
<CountRenderer />
</CounterProvider>
)
}
function CountRenderer () {
// get the context's value by using useContext()
// and passing the context as an argument
const currentValue = React.useContext(counterContext)
return (
<div>Value: {currentValue}</div>
)
}