Skip to content

Instantly share code, notes, and snippets.

@theham3d
Created November 1, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theham3d/9c761239120b480d92d56b9ab43f7ba8 to your computer and use it in GitHub Desktop.
Save theham3d/9c761239120b480d92d56b9ab43f7ba8 to your computer and use it in GitHub Desktop.
useReducer Example
import React , { useReducer } from 'react';
const initialState = {count: 0};
const yourReducer = (state, action) => {
switch (action.type) {
case 'reset':
return initialState;
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
}
}
const MyCounter = props => {
const [state, dispatch] = useReducer(yourReducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({type: 'reset'})}>Reset</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
</div>
);
}
export default MyCounter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment