react usereducer hook code example

Example 1: useReducer

function init(initialCount) {  return {count: initialCount};}
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    case 'reset':      return init(action.payload);    default:
      throw new Error();
  }
}

function Counter({initialCount}) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}>        Reset
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

Example 2: usestate or usereducer

//When it's just an independent element of state you're managing

useState

Example 3: usereducer hook

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};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

Example 4: react reducer hooks

import React from "react";

// initial state
const initialState = {counter: 0};

// action type
const INC = 'INCREMENT';
const DEC = 'DECREMENT';

// action creator inc
function incActionCreator() {
   return  {
       type: INC,
   }
}

// action creator dec
function decActionCreator() {
   return  {
       type: DEC,
   }
}

// action reducer
function hooksReducer(state, action) {
   switch(action.type) {
   case 'INCREMENT':
      return {
         ...state,
         counter: state.counter++
      }
      case 'DECREMENT':
         return {
            ...state,
            counter: state.counter--
         }
   default:
      return state;
   }
}

// app component
function App () {

  // useReducer is very similar to the store in Redux
  const [stateAction, setDispatchAction] = React.useReducer(hooksReducer, initialState);

  const incClick = (e) =>  setDispatchAction(incActionCreator())
  const decClick = (e) => setDispatchAction(decActionCreator())

  return (
    <>
      <button onClick={incClick}>Incerement</button>
      <button onClick={decClick}>Decrement</button>
      <h4>Counter: {stateAction.counter}</h4>
    </>
  );
}

export default App;