useReducer() Hook in React JS – Example & Explanation
Sridhar Raj P
?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ?? | JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver
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:
Basic Syntax of useReducer()
const [state, dispatch] = useReducer(reducerFunction, initialState);
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