Skip to content

Instantly share code, notes, and snippets.

@rockiger
Created February 19, 2021 08:38
Show Gist options
  • Select an option

  • Save rockiger/055a0f11d70f6cd69c9c792b8446ba2e to your computer and use it in GitHub Desktop.

Select an option

Save rockiger/055a0f11d70f6cd69c9c792b8446ba2e to your computer and use it in GitHub Desktop.

Revisions

  1. rockiger created this gist Feb 19, 2021.
    27 changes: 27 additions & 0 deletions Counter_useReducer.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    const initialState = {count: 0};
    function reducer(state, action) {
    switch (action.type) {
    case 'increment':
    return {count: state.count + 1};
    case 'decrement':
    return {count: state.count - 1};
    case 'set':
    return {count: action.count};
    case 'reset':
    return initialState;
    default:
    state;
    }
    }
    function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
    <>
    Count: {state.count}
    <button onClick={() => dispatch({type: 'reset'})}>Reset</button>
    <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    <button onClick={() => dispatch({type: 'increment'})}>+</button>
    <button onClick={() => dispatch({type: 'set', count: 25})}>Set to 25</button>
    </>
    );
    }