Skip to content

Instantly share code, notes, and snippets.

@juhahinkula
Created November 13, 2019 11:50
Show Gist options
  • Save juhahinkula/99df5f8cb2f0566318a929b5dfb762b8 to your computer and use it in GitHub Desktop.
Save juhahinkula/99df5f8cb2f0566318a929b5dfb762b8 to your computer and use it in GitHub Desktop.
Counter using useReducer
<!-- Fetch astronomy picture of the day from NASA API -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>React example</title>
</head>
<body>
<!-- Root container for react components -->
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel">
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function ReducerCounter() {
const [state, dispatch] = React.useReducer(reducer, {count: 0});
return (
<div>
Count: {state.count}
<br />
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</div>
);
}
ReactDOM.render(<ReducerCounter />, document.getElementById("root"));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment