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.

Syntax

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

Parameters

  • Reducer − The function to handle or update the state

  • initialArgs − Iitial state

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

Example

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.

App.jsx

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

const App = () => {
   const [ans, dispatch] = useReducer(reducer, initialState);
   return (
      <div>
         <h2>{ans}</h2>
         <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>
      </div>
   );
};
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.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 10:58:14
Advertisements