Advertisement
aldikhan13

React UserReducer Example

Jun 26th, 2020
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useReducer } from "react";
  2.  
  3. // initial state
  4. const initialState = {counter: 0};
  5.  
  6. // action type
  7. const INC = 'INCREMENT';
  8. const DEC = 'DECREMENT';
  9.  
  10. // action creator inc
  11. function incActionCreator() {
  12.    return  {
  13.        type: INC,
  14.    }
  15. }
  16.  
  17. // action creator dec
  18. function decActionCreator() {
  19.    return  {
  20.        type: DEC,
  21.    }
  22. }
  23.  
  24. // action reducer
  25. function hooksReducer(state, action) {
  26.    switch(action.type) {
  27.    case 'INCREMENT':
  28.       return {
  29.          ...state,
  30.          counter: state.counter++
  31.       }
  32.       case 'DECREMENT':
  33.          return {
  34.             ...state,
  35.             counter: state.counter--
  36.          }
  37.    default:
  38.       return state;
  39.    }
  40. }
  41.  
  42. // app component
  43. function App () {
  44.  
  45.   // useReducer is very similar to the store in Redux
  46.   const [stateAction, setDispatchAction] = useReducer(hooksReducer, initialState);
  47.  
  48.   const incClick = (e) =>  setDispatchAction(incActionCreator())
  49.   const decClick = (e) => setDispatchAction(decActionCreator())
  50.  
  51.   return (
  52.     <>
  53.       <button onClick={incClick}>Incerement</button>
  54.       <button onClick={decClick}>Decrement</button>
  55.       <h4>Counter: {stateAction.counter}</h4>
  56.     </>
  57.   );
  58. }
  59.  
  60. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement