Extracting State Logic into a Reducer·续1
button {
margin: 5px;
}
li {
list-style-type: none;
}
ul,
li {
margin: 0;
padding: 0;
}
If you want, you can even move the reducer to a different file:
```js src/App.js import { useReducer } from 'react'; import AddTask from './AddTask.js'; import TaskList from './TaskList.js'; import tasksReducer from './tasksReducer.js';
export default function TaskApp() { const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
function handleAddTask(text) { dispatch({ type: 'added', id: nextId++, text: text, }); }
function handleChangeTask(task) { dispatch({ type: 'changed', task: task, }); }
function handleDeleteTask(taskId) { dispatch({ type: 'deleted', id: taskId, }); }
return ( <>
Prague itinerary
let nextId = 3; const initialTasks = [ {id: 0, text: 'Visit Kafka Museum', done: true}, {id: 1, text: 'Watch a puppet show', done: false}, {id: 2, text: 'Lennon Wall pic', done: false}, ];
```js src/tasksReducer.js
export default function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [
...tasks,
{
id: action.id,
text: action.text,
done: false,
},
];
}
case 'changed': {
return tasks.map((t) => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter((t) => t.id !== action.id);
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
```js src/AddTask.js hidden import { useState } from 'react';
export default function AddTask({onAddTask}) { const [text, setText] = useState(''); return ( <> setText(e.target.value)} /> </> ); }
```js src/TaskList.js hidden
import { useState } from 'react';
export default function TaskList({tasks, onChangeTask, onDeleteTask}) {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
<Task task={task} onChange={onChangeTask} onDelete={onDeleteTask} />
</li>
))}
</ul>
);
}
function Task({task, onChange, onDelete}) {
const [isEditing, setIsEditing] = useState(false);
let taskContent;
if (isEditing) {
taskContent = (
<>
<input
value={task.text}
onChange={(e) => {
onChange({
...task,
text: e.target.value,
});
}}
/>
<button onClick={() => setIsEditing(false)}>Save</button>
</>
);
} else {
taskContent = (
<>
{task.text}
<button onClick={() => setIsEditing(true)}>Edit</button>
</>
);
}
return (
<label>
<input
type="checkbox"
checked={task.done}
onChange={(e) => {
onChange({
...task,
done: e.target.checked,
});
}}
/>
{taskContent}
<button onClick={() => onDelete(task.id)}>Delete</button>
</label>
);
}
button {
margin: 5px;
}
li {
list-style-type: none;
}
ul,
li {
margin: 0;
padding: 0;
}
Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify what happened by dispatching actions, and the reducer function determines how the state updates in response to them.
Comparing useState and useReducer
Reducers are not without downsides! Here's a few ways you can compare them:
- Code size: Generally, with
useStateyou have to write less code upfront. WithuseReducer, you have to write both a reducer function and dispatch actions. However,useReducercan help cut down on the code if many event handlers modify state in a similar way. - Readability:
useStateis very easy to read when the state updates are simple. When they get more complex, they can bloat your component's code and make it difficult to scan. In this case,useReducerlets you cleanly separate the how of update logic from the what happened of event handlers. - Debugging: When you have a bug with
useState, it can be difficult to tell where the state was set incorrectly, and why. WithuseReducer, you can add a console log into your reducer to see every state update, and why it happened (due to whichaction). If eachactionis correct, you'll know that the mistake is in the reducer logic itself. However, you have to step through more code than withuseState. - Testing: A reducer is a pure function that doesn't depend on your component. This means that you can export and test it separately in isolation. While generally it's best to test components in a more realistic environment, for complex state update logic it can be useful to assert that your reducer returns a particular state for a particular initial state and action.
- Personal preference: Some people like reducers, others don't. That's okay. It's a matter of preference. You can always convert between
useStateanduseReducerback and forth: they are equivalent!
We recommend using a reducer if you often encounter bugs due to incorrect state updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even useState and useReducer in the same component.
Writing reducers well
Keep these two tips in mind when writing reducers:
- Reducers must be pure. Similar to state updater functions, reducers run during rendering! (Actions are queued until the next render.) This means that reducers must be pure—same inputs always result in the same output. They should not send requests, schedule timeouts, or perform any side effects (operations that impact things outside the component). They should update objects and arrays without mutations.
- Each action describes a single user interaction, even if that leads to multiple changes in the data. For example, if a user presses "Reset" on a form with five fields managed by a reducer, it makes more sense to dispatch one
reset_formaction rather than five separateset_fieldactions. If you log every action in a reducer, that log should be clear enough for you to reconstruct what interactions or responses happened in what order. This helps with debugging!
Writing concise reducers with Immer
Just like with updating objects and arrays in regular state, you can use the Immer library to make reducers more concise. Here, useImmerReducer lets you mutate the state with push or arr[i] = assignment:
```js src/App.js import { useImmerReducer } from 'use-immer'; import AddTask from './AddTask.js'; import TaskList from './TaskList.js';
function tasksReducer(draft, action) { switch (action.type) { case 'added': { draft.push({ id: action.id, text: action.text, done: false, }); break; } case 'changed': { const index = draft.findIndex((t) => t.id === action.task.id); draft[index] = action.task; break; } case 'deleted': { return draft.filter((t) => t.id !== action.id); } default: { throw Error('Unknown action: ' + action.type); } } }
export default function TaskApp() { const [tasks, dispatch] = useImmerReducer(tasksReducer, initialTasks);
function handleAddTask(text) { dispatch({ type: 'added', id: nextId++, text: text, }); }
function handleChangeTask(task) { dispatch({ type: 'changed', task: task, }); }
function handleDeleteTask(taskId) { dispatch({ type: 'deleted', id: taskId, }); }
return ( <>
Prague itinerary
let nextId = 3; const initialTasks = [ {id: 0, text: 'Visit Kafka Museum', done: true}, {id: 1, text: 'Watch a puppet show', done: false}, {id: 2, text: 'Lennon Wall pic', done: false}, ];
```js src/AddTask.js hidden
import { useState } from 'react';
export default function AddTask({onAddTask}) {
const [text, setText] = useState('');
return (
<>
<input
placeholder="Add task"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button
onClick={() => {
setText('');
onAddTask(text);
}}>
Add
</button>
</>
);
}
```js src/TaskList.js hidden import { useState } from 'react';
export default function TaskList({tasks, onChangeTask, onDeleteTask}) { return (
-
{tasks.map((task) => (
-
function Task({task, onChange, onDelete}) { const [isEditing, setIsEditing] = useState(false); let taskContent; if (isEditing) { taskContent = ( <> { onChange({ ...task, text: e.target.value, }); }} /> </> ); } else { taskContent = ( <> {task.text} </> ); } return ( ); }
```css
button {
margin: 5px;
}
li {
list-style-type: none;
}
ul,
li {
margin: 0;
padding: 0;
}
```json package.json { "dependencies": { "immer": "1.7.3", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "use-immer": "0.5.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
Reducers must be pure, so they shouldn't mutate state. But Immer provides you with a special `draft` object which is safe to mutate. Under the hood, Immer will create a copy of your state with the changes you made to the `draft`. This is why reducers managed by `useImmerReducer` can mutate their first argument and don't need to return state.
- To convert from `useState` to `useReducer`:
1. Dispatch actions from event handlers.
2. Write a reducer function that returns the next state for a given state and action.
3. Replace `useState` with `useReducer`.
- Reducers require you to write a bit more code, but they help with debugging and testing.
- Reducers must be pure.
- Each action describes a single user interaction.
- Use Immer if you want to write reducers in a mutating style.
#### Dispatch actions from event handlers
Currently, the event handlers in `ContactList.js` and `Chat.js` have `// TODO` comments. This is why typing into the input doesn't work, and clicking on the buttons doesn't change the selected recipient.
Replace these two `// TODO`s with the code to `dispatch` the corresponding actions. To see the expected shape and the type of the actions, check the reducer in `messengerReducer.js`. The reducer is already written so you won't need to change it. You only need to dispatch the actions in `ContactList.js` and `Chat.js`.
The `dispatch` function is already available in both of these components because it was passed as a prop. So you need to call `dispatch` with the corresponding action object.
To check the action object shape, you can look at the reducer and see which `action` fields it expects to see. For example, the `changed_selection` case in the reducer looks like this:
```js
case 'changed_selection': {
return {
...state,
selectedId: action.contactId
};
}
This means that your action object should have a type: 'changed_selection'. You also see the action.contactId being used, so you need to include a contactId property into your action.
```js src/App.js import { useReducer } from 'react'; import Chat from './Chat.js'; import ContactList from './ContactList.js'; import { initialState, messengerReducer } from './messengerReducer';
export default function Messenger() { const [state, dispatch] = useReducer(messengerReducer, initialState); const message = state.message; const contact = contacts.find((c) => c.id === state.selectedId); return (
const contacts = [ {id: 0, name: 'Taylor', email: 'taylor@mail.com'}, {id: 1, name: 'Alice', email: 'alice@mail.com'}, {id: 2, name: 'Bob', email: 'bob@mail.com'}, ];
```js src/messengerReducer.js
export const initialState = {
selectedId: 0,
message: 'Hello',
};
export function messengerReducer(state, action) {
switch (action.type) {
case 'changed_selection': {
return {
...state,
selectedId: action.contactId,
message: '',
};
}
case 'edited_message': {
return {
...state,
message: action.message,
};
}
default: {
throw Error('Unknown action: ' + action.type);
}
}
}
```js src/ContactList.js export default function ContactList({contacts, selectedId, dispatch}) { return (
-
{contacts.map((contact) => (
- ))}
```js src/Chat.js
import { useState } from 'react';
export default function Chat({contact, message, dispatch}) {
return (
<section className="chat">
<textarea
value={message}
placeholder={'Chat to ' + contact.name}
onChange={(e) => {
// TODO: dispatch edited_message
// (Read the input value from e.target.value)
}}
/>
<br />
<button>Send to {contact.email}</button>
</section>
);
}
