The useReducer
Hook in React functions similarly to the useState
Hook but offers more robust state logic capabilities. It’s particularly useful for managing complex state changes and multiple state variables that depend on intricate logic.
Syntax
The useReducer
Hook takes two arguments:
useReducer(<reducerFunction>, <initialState>)
reducerFunction
: Defines your state update logic.initialState
: Sets the starting state, typically an object.
The useReducer
Hook returns an array containing the current state and a dispatch
function to trigger state updates.
Example
This only covers the logic to monitor the completion status of a task.
All the logic for adding, deleting, and completing tasks can be included in a single useReducer
Hook by incorporating additional actions.
import { useReducer } from "react"; import ReactDOM from "react-dom/client"; const initialTasks = [ { id: 1, title: "Task 1", complete: false, }, { id: 2, title: "Task 2", complete: false, }, ]; const taskReducer = (state, action) => { switch (action.type) { case "TOGGLE_COMPLETE": return state.map((task) => { if (task.id === action.id) { return { ...task, complete: !task.complete }; } return task; }); default: return state; } }; function TaskList() { const [tasks, dispatch] = useReducer(taskReducer, initialTasks); const handleToggle = (task) => { dispatch({ type: "TOGGLE_COMPLETE", id: task.id }); }; return ( <> {tasks.map((task) => ( <div key={task.id}> <label> <input type="checkbox" checked={task.complete} onChange={() => handleToggle(task)} /> {task.title} </label> </div> ))} </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<TaskList />);