Skip to content

Instantly share code, notes, and snippets.

@Sergioamjr
Last active December 28, 2018 01:45
Show Gist options
  • Save Sergioamjr/037f946c2dac14371710d2735ab23c90 to your computer and use it in GitHub Desktop.
Save Sergioamjr/037f946c2dac14371710d2735ab23c90 to your computer and use it in GitHub Desktop.
useReducer example from React Hooks
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action) {
case "add":
return { count: state.count + 1 };
case "sub":
return { count: state.count - 1 };
default:
return state;
}
}
function UseReducerComponent() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch("add")}>Add</button>
<button onClick={() => dispatch("sub")}>Sub</button>
</div>
);
}
export default UseReducerComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment