Open In App
Related Articles

ReactJS useReducer Hook

Improve Article
Save Article
Like 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.


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:


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;
      throw new Error("Unexpected action");
const App = () => {
    // Initialising useReducer hook
  const [count, dispatch] = useReducer(reducer, initialState);
  return (
      <button onClick={() => dispatch("add")}>
      <button onClick={() => dispatch("subtract")}>
      <button onClick={() => dispatch("reset")}>
export default App;


Last Updated : 03 Aug, 2021
Like Article
Save Article
Similar Reads
Related Tutorials