useReducer·续
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 ( <> <h1>Prague itinerary</h1> <AddTask onAddTask={handleAddTask} /> <TaskList tasks={tasks} onChangeTask={handleChangeTask} onDeleteTask={handleDeleteTask} /> </> ); }
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 ( <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> ); }
```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" } }
---
### Avoiding recreating the initial state
React saves the initial state once and ignores it on the next renders.
```js
function createInitialState(username) {
// ...
}
function TodoList({ username }) {
const [state, dispatch] = useReducer(reducer, createInitialState(username));
// ...
Although the result of createInitialState(username) is only used for the initial render, you're still calling this function on every render. This can be wasteful if it's creating large arrays or performing expensive calculations.
To solve this, you may pass it as an initializer function to useReducer as the third argument instead:
```js {6} function createInitialState(username) { // ... }
function TodoList({ username }) { const [state, dispatch] = useReducer(reducer, username, createInitialState); // ...
Notice that you’re passing `createInitialState`, which is the *function itself*, and not `createInitialState()`, which is the result of calling it. This way, the initial state does not get re-created after initialization.
In the above example, `createInitialState` takes a `username` argument. If your initializer doesn't need any information to compute the initial state, you may pass `null` as the second argument to `useReducer`.
#### Passing the initializer function
This example passes the initializer function, so the `createInitialState` function only runs during initialization. It does not run when component re-renders, such as when you type into the input.
```js src/App.js hidden
import TodoList from './TodoList.js';
export default function App() {
return <TodoList username="Taylor" />;
}
```js src/TodoList.js active import { useReducer } from 'react';
function createInitialState(username) { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, text: username + "'s task #" + (i + 1) }); } return { draft: '', todos: initialTodos, }; }
function reducer(state, action) { switch (action.type) { case 'changed_draft': { return { draft: action.nextDraft, todos: state.todos, }; }; case 'added_todo': { return { draft: '', todos: [{ id: state.todos.length, text: state.draft }, ...state.todos] } } } throw Error('Unknown action: ' + action.type); }
export default function TodoList({ username }) { const [state, dispatch] = useReducer( reducer, username, createInitialState ); return ( <> <input value={state.draft} onChange={e => { dispatch({ type: 'changed_draft', nextDraft: e.target.value }) }} /> <button onClick={() => { dispatch({ type: 'added_todo' }); }}>Add</button> <ul> {state.todos.map(item => ( <li key={item.id}> {item.text} </li> ))} </ul> </> ); }
#### Passing the initial state directly
This example **does not** pass the initializer function, so the `createInitialState` function runs on every render, such as when you type into the input. There is no observable difference in behavior, but this code is less efficient.
```js src/App.js hidden
import TodoList from './TodoList.js';
export default function App() {
return <TodoList username="Taylor" />;
}
```js src/TodoList.js active import { useReducer } from 'react';
function createInitialState(username) { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, text: username + "'s task #" + (i + 1) }); } return { draft: '', todos: initialTodos, }; }
function reducer(state, action) { switch (action.type) { case 'changed_draft': { return { draft: action.nextDraft, todos: state.todos, }; }; case 'added_todo': { return { draft: '', todos: [{ id: state.todos.length, text: state.draft }, ...state.todos] } } } throw Error('Unknown action: ' + action.type); }
export default function TodoList({ username }) { const [state, dispatch] = useReducer( reducer, createInitialState(username) ); return ( <> <input value={state.draft} onChange={e => { dispatch({ type: 'changed_draft', nextDraft: e.target.value }) }} /> <button onClick={() => { dispatch({ type: 'added_todo' }); }}>Add</button> <ul> {state.todos.map(item => ( <li key={item.id}> {item.text} </li> ))} </ul> </> ); }
---
## Troubleshooting
### I've dispatched an action, but logging gives me the old state value
Calling the `dispatch` function **does not change state in the running code**:
```js {4,5,8}
function handleClick() {
console.log(state.age); // 42
dispatch({ type: 'incremented_age' }); // Request a re-render with 43
console.log(state.age); // Still 42!
setTimeout(() => {
console.log(state.age); // Also 42!
}, 5000);
}
This is because states behaves like a snapshot. Updating state requests another render with the new state value, but does not affect the state JavaScript variable in your already-running event handler.
If you need to guess the next state value, you can calculate it manually by calling the reducer yourself:
const action = { type: 'incremented_age' };
dispatch(action);
const nextState = reducer(state, action);
console.log(state); // { age: 42 }
console.log(nextState); // { age: 43 }
I've dispatched an action, but the screen doesn't update
React will ignore your update if the next state is equal to the previous state, as determined by an Object.is comparison. This usually happens when you change an object or an array in state directly:
```js {4-5,9-10} function reducer(state, action) { switch (action.type) { case 'incremented_age': { // 🚩 Wrong: mutating existing object state.age++; return state; } case 'changed_name': { // 🚩 Wrong: mutating existing object state.name = action.nextName; return state; } // ... } }
You mutated an existing `state` object and returned it, so React ignored the update. To fix this, you need to ensure that you're always [updating objects in state](/learn/updating-objects-in-state) and [updating arrays in state](/learn/updating-arrays-in-state) instead of mutating them:
```js {4-8,11-15}
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ✅ Correct: creating a new object
return {
...state,
age: state.age + 1
};
}
case 'changed_name': {
// ✅ Correct: creating a new object
return {
...state,
name: action.nextName
};
}
// ...
}
}
A part of my reducer state becomes undefined after dispatching
Make sure that every case branch copies all of the existing fields when returning the new state:
```js {5} function reducer(state, action) { switch (action.type) { case 'incremented_age': { return { ...state, // Don't forget this! age: state.age + 1 }; } // ...
Without `...state` above, the returned next state would only contain the `age` field and nothing else.
---
### My entire reducer state becomes undefined after dispatching
If your state unexpectedly becomes `undefined`, you're likely forgetting to `return` state in one of the cases, or your action type doesn't match any of the `case` statements. To find why, throw an error outside the `switch`:
```js {10}
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ...
}
case 'edited_name': {
// ...
}
}
throw Error('Unknown action: ' + action.type);
}
You can also use a static type checker like TypeScript to catch such mistakes.
I'm getting an error: "Too many re-renders"
You might get an error that says: Too many re-renders. React limits the number of renders to prevent an infinite loop. Typically, this means that you're unconditionally dispatching an action during render, so your component enters a loop: render, dispatch (which causes a render), render, dispatch (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler:
```js {1-2} // 🚩 Wrong: calls the handler during render return <button onClick={handleClick()}>Click me</button>
// ✅ Correct: passes down the event handler return <button onClick={handleClick}>Click me</button>
// ✅ Correct: passes down an inline function return <button onClick={(e) => handleClick(e)}>Click me</button>
If you can't find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `dispatch` function call responsible for the error.
---
### My reducer or initializer function runs twice
In [Strict Mode](/reference/react/StrictMode), React will call your reducer and initializer functions twice. This shouldn't break your code.
This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and reducer functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes.
For example, this impure reducer function mutates an array in state:
```js {4-6}
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// 🚩 Mistake: mutating state
state.todos.push({ id: nextId++, text: action.text });
return state;
}
// ...
}
}
Because React calls your reducer function twice, you'll see the todo was added twice, so you'll know that there is a mistake. In this example, you can fix the mistake by replacing the array instead of mutating it:
js {4-11}
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// ✅ Correct: replacing with new state
return {
...state,
todos: [
...state.todos,
{ id: nextId++, text: action.text }
]
};
}
// ...
}
}
Now that this reducer function is pure, calling it an extra time doesn't make a difference in behavior. This is why React calling it twice helps you find mistakes. Only component, initializer, and reducer functions need to be pure. Event handlers don't need to be pure, so React will never call your event handlers twice.
Read keeping components pure to learn more.
