Welcome back to CodeYourCraft! Today, we're diving into a powerful feature of React JS called useReducer. This tool is a great way to manage state in your applications, especially when dealing with complex data and multiple components. Let's get started!
useReducer is a React hook that helps you manage state in a predictable way, especially for applications with multiple components and complex state. It allows you to define a reducer function that handles state changes and multiple actions.
useState is a simpler hook used for managing simple state in a single component.useReducer is more suitable for managing complex state across multiple components and handling multiple actions.To use useReducer, first, you'll define a reducer function that handles state changes based on actions. Then, you'll use the useReducer hook to manage the state and dispatches actions to the reducer.
import React, { useState } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
export default Counter;š” Pro Tip: Don't forget to define your initial state in the reducer function!
In this example, we'll create a simple To-Do list app using useReducer.
import React, { useState } from 'react';
const initialState = {
tasks: [{ text: 'Learn React' }],
};
function reducer(state, action) {
switch (action.type) {
case 'add-task':
return { tasks: [...state.tasks, { text: action.text }] };
case 'remove-task':
return {
tasks: state.tasks.filter((task) => task.text !== action.text),
};
default:
throw new Error();
}
}
function ToDoList() {
const [state, dispatch] = useReducer(reducer, initialState);
const handleAddTask = (text) => {
dispatch({ type: 'add-task', text });
};
const handleRemoveTask = (text) => {
dispatch({ type: 'remove-task', text });
};
return (
<>
<h2>To-Do List</h2>
{state.tasks.map((task, index) => (
<li key={index}>
{task.text}
<button onClick={() => handleRemoveTask(task.text)}>Remove</button>
</li>
))}
<input type="text" placeholder="Add a task" />
<button onClick={() => handleAddTask(state.tasks[0].text)}>Add</button>
</>
);
}
export default ToDoList;What is useReducer in React JS?
What is the difference between useReducer and useState?
That's it for today! In the next lesson, we'll dive deeper into useReducer and explore more advanced concepts. Stay tuned and happy coding! š”