useReducer() Hook in React JS – Example & Explanation

useReducer() Hook in React JS – Example & Explanation

useReducer() Hook in React JS – Example & Explanation

The useReducer() hook is an alternative to useState() for managing complex state logic in React functional components. It’s useful when:

  • State changes depend on previous state
  • Multiple state values need to be updated together
  • State management logic is complex


Basic Syntax of useReducer()

const [state, dispatch] = useReducer(reducerFunction, initialState);

  • state → Holds the current state.
  • dispatch → Function to update state by sending an action.
  • reducerFunction → Defines how the state updates based on actions.
  • initialState → The default value of state.


Complex Example: Todo List with useReducer()

Here’s an advanced example where we use useReducer() to add, remove, and toggle todos.

1. Create TodoList.js

import React, { useReducer, useState } from "react";

// Initial state: Empty todo list

const initialState = [];

// Reducer function

const todoReducer = (state, action) => {

switch (action.type) {

case "ADD":

return [...state, { id: Date.now(), text: action.payload, completed: false }];

case "REMOVE":

return state.filter(todo => todo.id !== action.payload);

case "TOGGLE":

return state.map(todo =>

todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo

);

default:

return state;

}

};

function TodoList() {

const [todos, dispatch] = useReducer(todoReducer, initialState);

const [text, setText] = useState("");

const addTodo = () => {

if (text.trim() !== "") {

dispatch({ type: "ADD", payload: text });

setText("");

}

};

return (

<div>

<h2>Todo List</h2>

<input value={text} onChange={(e) => setText(e.target.value)} placeholder="New todo" />

<button onClick={addTodo}>Add</button>

<ul>

{todos.map((todo) => (

<li key={todo.id} style={{ textDecoration: todo.completed ? "line-through" : "none" }}>

{todo.text}

<button onClick={() => dispatch({ type: "TOGGLE", payload: todo.id })}>?</button>

<button onClick={() => dispatch({ type: "REMOVE", payload: todo.id })}>?</button>

</li>

))}

</ul>

</div>

);

}

export default TodoList;


2. Use TodoList in App.js

import React from "react";

import TodoList from "./TodoList";

function App() {

return (

<div>

<h1>useReducer Todo List</h1>

<TodoList />

</div>

);

}

export default App;


Why Use useReducer() Instead of useState()?

Conclusion

? useReducer() is useful for complex state logic

? Uses a reducer function instead of multiple useState() calls

要查看或添加评论,请登录

Sridhar Raj P的更多文章

  • Custom Hook

    Custom Hook

    Custom Hooks are a powerful feature introduced in React 16.8 that allow developers to extract and reuse stateful logic…

  • useReducer() Hook in React JS – Example & Explanation

    useReducer() Hook in React JS – Example & Explanation

    Hook in React JS – Example & Explanation The hook is an alternative to for managing complex state logic in React…

  • Passing Data from Child to Parent Component in React JS using Hooks

    Passing Data from Child to Parent Component in React JS using Hooks

    Passing Data from Child to Parent Component in React JS using Hooks In React, data flows from parent to child via…

  • Lists and Keys in React JS

    Lists and Keys in React JS

    In React, we use lists to render multiple components dynamically, and keys help React identify which items have…

    1 条评论
  • Object State Management

    Object State Management

    Object State Management Managing object state with in React is common when handling complex data structures like user…

  • useState Example

    useState Example

    Here are examples of using the hook in React functional components. Each example demonstrates a different use case.

  • Examples of using the useState hook in React Functional Components

    Examples of using the useState hook in React Functional Components

    Examples of using the useState hook in React Functional Components 1. Counter Example - ? Basic counter with increment…

  • Array, Array of Objects Values using Functional Component

    Array, Array of Objects Values using Functional Component

    Example 1: Displaying an Array of Strings import React from react; const FruitsList = () = { const fruits = [Apple…

    1 条评论
  • Hooks

    Hooks

    What are Hooks in React JS? Hooks in React allow functional components to manage state and side effects, which were…

  • State in Functional Components (useState Hook)

    State in Functional Components (useState Hook)

    State in Functional Components (useState Hook) In functional components, state is managed using the hook instead of and…

社区洞察