ReactJS – useReducer Hook

Page Content:
1.Introduction
2.Syntax
3.Use-Case for useReducer

1.Introduction:

1.useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
2.useReducer is an alternative to useState, it accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.


2.Syntax:

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

Here,
reducer − The function to handle or update the state based on action
initialArgs − Initial state
Init − To load the state lazily or when it is required


3.Use-Case for useReducer:

To get it working, we need to do a few things:

A)Define an initial state:

There are two ways to define initial state for useReducer:

1)Passing Initial state as Argument.

const [state, dispatch] = useReducer(
    reducer,
    {count: initialCount}
  );

2)Lazy Initialization:
    You can also create the initial state lazily. To do this, you can pass an init function as the third argument. The initial state will be set to init(initialArg).

function init(initialCount) {
  return {count: initialCount};
}
const [state, dispatch] = useReducer(reducer, initialCount, init);

B)Provide a function(reducer) that contains actions that update the state:

    reducer is that it will always only return one value. The job of a reducer is to reduce. That one value can be a number, a string, an array, or an object, but it will always only be one.

    Here reducer will return a single value based on the action provided:

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

c)Dispatch an updated state that is calculated relative to the initial state:

<button onClick={() => dispatch({type: 'decrement'})}>-</button>

Complete Code for useReducer Hook usage:

import React ,{useReducer} from 'react';
const initialState = {count: 0};   

function reducer(state, action) {
   console.log("Action called>>"+action.type);
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

export default App;


Final Output:

Leave a Reply