Front End Technology ‐ React.JS ‐ 10 - kumar28sahu03atish01/Programming-Beginner-To-Master GitHub Wiki

useReducer Hook In React

The useReducer Hook in React is used to manage complex state logic more centrally and predictably. It is similar to the useState Hook, but instead of directly modifying the state, it uses a reducer function to update it based on the action dispatched to it.

Compare & Contrast The useState & useReducer Hooks

Purpose

  1. useState: useState manages a simple state where the next state depends only on the previous state. It is suitable for managing independent pieces of state or state that do not require complex transitions.

  2. useReducer: useReducer is used for managing complex state logic where the next state depends on both the previous state and an action. It is suitable for managing a state that involves multiple actions and complex state transitions.

State Updates

  1. useState: With useState, state updates are done by directly calling the state setter function and passing the new state value.

  2. useReducer: With useReducer, state updates are done by dispatching actions to a reducer function, which then returns the new state based on the current state and the action.

Redability & Maintainability

  1. useState: useState is simpler and easier to use for managing a simple state. It can lead to more concise and readable code for simple state management.

  2. useReducer: useReducer can be more complex and require more boilerplate code, especially for managing complex state logic. However, it can lead to more maintainable code for complex state management as it centralizes the state logic in a single reducer function.

Performance

  1. useState: For simple state management, useState may be more performant as it does not involve the additional overhead of a reducer function.

  2. useReducer: For complex state management, useReducer may be more performant as it can lead to more efficient updates, especially when the state logic involves multiple actions and transitions.

useReducer Example 01

Create A Reducer Function

export const initialState = {
    count: 0
}

export const Reducer = (state, action) => {
    switch(action.type) {
        case "Increment":
            return {
                count: state.count += 1
            }
        
        case "Decrement":
            return {
                count: state.count -= 1
            }

        default:
            throw new Error();
    }
}

Use The Reducer Function Using useReducer

import { useReducer } from "react";
import { Reducer, initialState } from "./Reducer";

export const Exp1 = () => {
    const [state, dispatch] = useReducer(Reducer, initialState);
    return(
        <>
            <div style={{border:"2px solid black",margin:"10px",padding:"10px",display:"flex"}}>
                <button style={{margin:"10px"}} onClick={()=> dispatch({type:"Increment"})}>+</button>
                <p>{state.count}</p>
                <button style={{margin:"10px"}} onClick={()=> dispatch({type:"Decrement"})}>-</button>
            </div>
        </>
    );
}

useReducer Example 02

Create Action Statements

export const CREATE = "Create";
export const MAP = "Map";
export const FILTER = "Filter";
export const REDUCE = "Reducer";

Create Reducer Function

import { CREATE, FILTER, MAP, REDUCE } from "./ActionType";

export const InitialState = {
    array: [],
    result: null
};

export const Reducer = (state, action) => {
    switch(action.type) {
        case CREATE:
            return {
                ...state,
                array: [...state.array, action.payload]
            }

        case MAP:
            return {
                ...state,
                array: state.array.map(action.payload)
            }

        case FILTER:
            return {
                ...state,
                array: state.array.filter(action.payload).map(item => item * item)
            }

        case REDUCE:
            return{
                ...state,
                result: state.array.reduce(action.payload, 0)
            }
    }
}

Use The Reducer Function Using useReducer

import { useReducer, useState } from "react";
import { InitialState, Reducer } from "./Components/Reducer";
import { CREATE, DISPLAY, FILTER, MAP, REDUCE } from "./Components/ActionType";

export const App = () => {

  const [IP, SetIP] = useState("");
  const [state, dispatch] = useReducer(Reducer, InitialState);

  const SubmitHandler = (e) => {
    e.preventDefault();
    const Value = parseInt(IP);

    dispatch({
      type: CREATE,
      payload: Value,
    });

    SetIP("");
  };

  const MapHandler = () => {
    dispatch({
      type: MAP,
      payload: (item) => Number(item) * 2
    });
  };

  const FilterHandler = () => {
    dispatch({
      type: FILTER,
      payload: (item) => Number(item % 2 === 0)
    })
  }

  const ReduceHandler = () => {
    dispatch({
      type: REDUCE,
      payload: (acc, item) => Number(acc + item),
    })
  }

  return (
    <>
      <h1>React Front-End Development</h1>

      <div>
        <form onSubmit={SubmitHandler}>
          <input type="text" placeholder="Enter Array Element" onChange={(e)=>SetIP(e.target.value)} value={IP} />
          <input type="submit" value="Submit" />
        </form>
      </div>
      <div>
        <h2>Array</h2>
        <div>
          <button onClick={MapHandler}>Map</button>
          <button onClick={FilterHandler}>Filter</button>
          <button onClick={ReduceHandler}>Reducer</button>
        </div>
        <div style={{display: "flex"}}>
          {state.array.map((item, index) => (
            <div key={index}>
              <p style={{margin: "10px"}}>{item}</p>
            </div>
          ))}
        </div>
        <div>
          {state.result !== null &&(
            <div>
              {state.result}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
export default App;
⚠️ **GitHub.com Fallback** ⚠️