The useReducer
Hook in React works similarly to useState
, but provides enhanced state management capabilities. It is especially useful for handling complex state transitions and multiple interdependent state variables.
Syntax
The useReducer
Hook takes two arguments:
JavaScript
x
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.
JavaScript
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 />);