Skip to content
Related Articles
Open in App
Not now

Related Articles

ReactJS useReducer Hook

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2021
Improve Article
Save Article

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:

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!