ReactJS – useReducer hook

ReactJSWeb DevelopmentFront End Technology

This hook is a better alternative of the useState hook, as it is used when we want to attach a function along with handling the state or when we want to handle the state based on the previous values.


const [state, dispatch] = useReducer(reducer, initialArgs, init);


  • Reducer − The function to handle or update the state

  • initialArgs − Iitial state

  • Init − To load the state lazily or when it is required


In this example, we will build a simple calculator using the useReducer hook which takes the input from the user and displays the result accordingly.


import React, { useReducer } from 'react';

const initialState = 0;

const reducer = (state, action) => {
   switch (action) {
      case 1:
         return state + 1;
      case 2:
         return state + 2;
      case 3:
         return state + 3;
      case 'Reset':
         return 0;
      throw new Error('Error');

const App = () => {
   const [ans, dispatch] = useReducer(reducer, initialState);
   return (
         <button onClick={() => dispatch(1)}>Add 1</button>
         <button onClick={() => dispatch(2)}>Add 2</button>
         <button onClick={() => dispatch(3)}>Add 3</button>
         <button onClick={() => dispatch('Reset')}>reset</button>
export default App;

In the above example, when the user clicks on any button then the action is dispatched which updates the state and displays the updated state accordingly.


This will produce the following result.

Updated on 19-Mar-2021 10:58:54