<div id="root"></div>
const {useContext, useReducer} = React
const Context = React.createContext()
const reducer = (state, action) => {
switch(action.type) {
case "INSC":
return {state, data: ++state.data}
case "DESC":
return {state, data: --state.data}
default:
return state
}
}
const initState = {
data: 0
}
function Provider(props) {
const [state, dispatch] = useReducer(reducer, initState)
return (
<Context.Provider value={{state, dispatch}}>
{props.children}
</Context.Provider>
)
}
function Children() {
const {state, dispatch} = useContext(Context)
const add = () => {
dispatch({type: "INSC"})
}
const substract = () => {
dispatch({type: "DESC"})
}
return (
<div>
<div>{state.data}</div>
<button onClick={add}>+1</button>
<button onClick={substract}>-1</button>
</div>
)
}
ReactDOM.render(<Provider><Children /></Provider>, document.getElementById("root"))
View Compiled
This Pen doesn't use any external CSS resources.