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:


Similar Reads

Purpose of useReducer hook in React
The useReducer hook is a state management hook in React that provides an alternative to the useState hook. It is used when the state of a component is complex and requires more than one state variable. Syntax:const [state, dispatch] = useReducer(reducer, initialState, init)reducer: The reducer is a function responsible for defining how the state tr
3 min read
How to use useReducer within a custom hook?
useReducer is one of the fundamental built-in hooks in React, primarily used for managing complex state logic within functional components. Using useReducer within a custom hook is quite similar to using it in a regular functional component. Understanding the concept of useReducert within a custom hook:Create your custom hook: First, you define a J
2 min read
Difference between useState and useReducer
React offers powerful tools, like `useState` for simple tasks making it a friendly companion, and `useReducer` for complex challenges, functioning like a superhero team. While both manage information, `useState` is ideal for everyday simplicity, resembling a sticky note, while `useReducer` shines in intricate scenarios, handling simultaneous comple
4 min read
What is the benefit of using useReducer with context?
Using useReducer with context in React allows for centralized state management, predictable state updates through dispatching actions, encapsulated logic for state transitions, optimized performance by preventing unnecessary re-renders, and easier testing due to the pure nature of reducers. This approach promotes cleaner, more maintainable, and eff
2 min read
How to combine useContext with useReducer?
Combining useContext with useReducer in React allows you to manage a global state more effectively by providing a centralized state management solution. How to combine useContext with useReducer?Create a Context: First, you need to create a context to hold your global state and provide it to your component tree. You can use the React.createContext(
3 min read
How does useReducer help manage complex state in React components?
useReducer is a React hook that provides an alternative approach to managing state in components compared to useState. While useState is easy and suitable for managing simple state updates, useReducer and is particularly helpful for managing more complex state logic. Managing Complex State in React with useReducer:Centralized State Logic: With useR
2 min read
How to handle complex state logic with useReducer?
useReducer hook is a powerful alternative to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It's particularly useful when the state logic involves more than just simple state updates. Handling complex state logic with useReducer in React involves defining a reducer fu
3 min read
What is the use of useReducer ?
useReducer is a tool in React that helps manage the state in a more organized way. It's like a central hub where you can handle different changes to your state based on various actions. One example use case for 'useReducer' in React is managing a shopping cart state. You can use 'useReducer' to handle actions like adding items to the cart, removing
6 min read
ReactJS useContext Hook
Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes). Context API u
2 min read
ReactJS useId Hook
React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application: Step 1: Create a react project folder, for that op
3 min read
Article Tags :