react js-tutorial

React useReducer Hook

One of the extra Hooks included with React v16.8 is useReducer. UseReducer, an alternative to the useState Hook, aids in the management of intricate state logic in React applications. UseReducer can be a good substitute for Redux, Recoil, or MobX when paired with other Hooks like useContext. In some circumstances, it is clearly the superior choice.

While Redux, Recoil, and MobX are frequently the best alternatives for maintaining global state in large React applications, many React developers frequently do so when Hooks would have been a more efficient way to handle their information.

Managing state with React Hooks and the Context API becomes quite an enticing alternative when you take into account the difficulty of getting started with a third-party library like Redux, which is made much easier with Redux Toolkit. To maintain global state in our programme, there is no need to add numerous files and folders or install an external software.

The golden rule is still relevant, though. Redux for application state, component state for component state. This tutorial will examine the usage of Reviewing the situations in which you should and shouldn’t utilise Reducer Hook in detail. Let’s get going!

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.

Program to demonstrate the use of useReducer Hook:

App.js

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:

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.