Open In App

ReactJS useReducer Hook

Last Updated : 03 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized.

The useReducer hook takes three arguments including reducer, initial state, and the function to load the initial state lazily.

Syntax:

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

Example: Here reducer is the user-defined function that pairs the current state with the dispatch method to handle the state, initialArgs refers to the initial arguments and init is the function to initialize the state lazily.

App.js: Program to demonstrate the use of useReducer Hook:

Javascript




import React, { useReducer } from "react";
 
// Defining the initial state and the reducer
const initialState = 0;
const reducer = (state, action) => {
  switch (action) {
    case "add":
      return state + 1;
    case "subtract":
      return state - 1;
    case "reset":
      return 0;
    default:
      throw new Error("Unexpected action");
  }
};
 
const App = () => {
    // Initialising useReducer hook
  const [count, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={() => dispatch("add")}>
        add
      </button>
      <button onClick={() => dispatch("subtract")}>
        subtract
      </button>
      <button onClick={() => dispatch("reset")}>
        reset
      </button>
    </div>
  );
};
 
export default App;


Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads