<div id="root">
</div>
const CountContext = React.createContext();
const reducer = (state, action) => {
switch(action.type) {
case 'increment':
return {
count: state.count + 1
};
case 'decrement':
return {
count: state.count - 1
};
default:
return {
count: 0
}
}
}
const initialState = {
count: 0,
};
const Child = () => {
const [state, dispatch] = React.useContext(CountContext);
return (
<div>
Child Count: {state.count}
<br />
<button type="button" className="bg-blue-400 p-4 text-white hover:bg-blue-700" onClick={() => dispatch({ type: "decrement" })}>Decrement</button>|
<button type="button" className="bg-blue-400 p-4 text-white hover:bg-blue-700" onClick={() => dispatch({ type: "increment" })}>Increment</button>
</div>
);
}
const App = () => {
const countReducer = React.useReducer(reducer, initialState);
return (
<div>
App Count: {countReducer[0].count}
<br />
<CountContext.Provider value={countReducer}>
<Child />
</CountContext.Provider>
</div>
);
}
const root = ReactDOM.createRoot(document.querySelector('#root'));
root.render(<App />);
View Compiled
This Pen doesn't use any external CSS resources.