Learn the useReducer hook in 5 minutes with simple example [video]

Hey everyone 👋🏻,

In this article, let us understand the useReducer hook in React.js.

CODE for the video:

Let us understand the first code down below. Here we are using the useReducer hook to setup a state for our counter with a default initial value of 0 to begin with. Also we have our counterReducer function, which by default gets the state implicitly passed to it by React and the second argument is the value, so something that we dispatch from our two buttons.

So we have two buttons, one for INCREMENT and other one for DECREMENT. So the first button increments the value of counter by 1 whereas the second button decrements the value of counter by 1.
Now we can improve this by write a more declarative code to achieve this.

import { useReducer, Fragment } from "react"; 

function counterReducer(state, value) { 
  return state + value;
}

function ReducerCounter() { 

  const [counter, dispatch] = useReducer(counterReducer, 0); 

  return (
    <Fragment>
       <h1>Count: {counter} </h1>
       <button onClick={() => dispatch(1)}>Increment</button>
       <button onClick={() => dispatch(-1)}>Decrement</button>
    </Fragment>
  )
}



export default ReducerCounter;

So here is the second code snippet. Here instead of dispatching a value we are dispatching an action with the type property. So we are just declaring and hence decoupling our state updating logic from the component.

import { useReducer, Fragment } from "react"; 


function counterReducer(state, action) { 
    if(action.type === 'INCREMENT') { 
      return state + 1;
    }else if(action.type === 'DECREMENT'){ 
      return state - 1; 
    }else if(action.type === 'RESET') { 
      return 0;
    }
  }

function ReducerCounter() { 

  const [counter, dispatch] = useReducer(counterReducer, 0); 

  return (
    <Fragment>
       <h1>Count: {counter} </h1>
       <button onClick={() => dispatch({type: 'INCREMENT'})}>Increment</button>
       <button onClick={() => dispatch({ type: 'DECREMENT'})}>Decrement</button>
       <button onClick={() => dispatch({ type: 'RESET'})}>Reset</button>
    </Fragment>
  )
}

export default ReducerCounter;

So for detailed understanding, please check the complete video that explains the above example.

📺 VIDEO

Thanks for reading !

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Follow me on Instagram: https://instagram.com/thenerdydev
👉🏻 Check out my YouTube Channel : https://youtube.com/thenerdydev

17