useReducer
useReducer is a React Hook that lets you add a reducer to your component.
const [state, dispatch] = useReducer(reducer, initialArg, init?)
Reference
useReducer(reducer, initialArg, init?)
Call useReducer at the top level of your component to manage its state with a reducer.
import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
// ...
Parameters
reducer: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types.initialArg: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the nextinitargument.- optional
init: The initializer function that should return the initial state. If it's not specified, the initial state is set toinitialArg. Otherwise, the initial state is set to the result of callinginit(initialArg).
Returns
useReducer returns an array with exactly two values:
- The current state. During the first render, it's set to
init(initialArg)orinitialArg(if there's noinit). - The
dispatchfunction that lets you update the state to a different value and trigger a re-render.
Caveats
useReduceris a Hook, so you can only call it at the top level of your component or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.- The
dispatchfunction has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. Learn more about removing Effect dependencies. - In Strict Mode, React will call your reducer and initializer twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored.
dispatch function
The dispatch function returned by useReducer lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the dispatch function:
const [state, dispatch] = useReducer(reducer, { age: 42 });
function handleClick() {
dispatch({ type: 'incremented_age' });
// ...
React will set the next state to the result of calling the reducer function you've provided with the current state and the action you've passed to dispatch.
Parameters
action: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with atypeproperty identifying it and, optionally, other properties with additional information.
Returns
dispatch functions do not have a return value.
Caveats
-
The
dispatchfunction only updates the state variable for the next render. If you read the state variable after calling thedispatchfunction, you will still get the old value that was on the screen before your call. -
If the new value you provide is identical to the current
state, as determined by anObject.iscomparison, React will skip re-rendering the component and its children. This is an optimization. React may still need to call your component before ignoring the result, but it shouldn't affect your code. -
React batches state updates. It updates the screen after all the event handlers have run and have called their
setfunctions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can useflushSync.
Usage
Adding a reducer to a component
Call useReducer at the top level of your component to manage state with a reducer.
```js [[1, 8, "state"], [2, 8, "dispatch"], [4, 8, "reducer"], [3, 8, "{ age: 42 }"]] import { useReducer } from 'react';
function reducer(state, action) { // ... }
function MyComponent() { const [state, dispatch] = useReducer(reducer, { age: 42 }); // ...
`useReducer` returns an array with exactly two items:
1. The <CodeStep step={1}>current state</CodeStep> of this state variable, initially set to the <CodeStep step={3}>initial state</CodeStep> you provided.
2. The <CodeStep step={2}>`dispatch` function</CodeStep> that lets you change it in response to interaction.
To update what's on the screen, call <CodeStep step={2}>`dispatch`</CodeStep> with an object representing what the user did, called an *action*:
```js [[2, 2, "dispatch"]]
function handleClick() {
dispatch({ type: 'incremented_age' });
}
React will pass the current state and the action to your <CodeStep step={4}>reducer function</CodeStep>. Your reducer will calculate and return the next state. React will store that next state, render your component with it, and update the UI.
import { useReducer } from 'react';
function reducer(state, action) {
if (action.type === 'incremented_age') {
return {
age: state.age + 1
};
}
throw Error('Unknown action.');
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
return (
<>
<button onClick={() => {
dispatch({ type: 'incremented_age' })
}}>
Increment age
</button>
<p>Hello! You are {state.age}.</p>
</>
);
}
button { display: block; margin-top: 10px; }
useReducer is very similar to useState, but it lets you move the state update logic from event handlers into a single function outside of your component. Read more about choosing between useState and useReducer.
Writing the reducer function
A reducer function is declared like this:
function reducer(state, action) {
// ...
}
Then you need to fill in the code that will calculate and return the next state. By convention, it is common to write it as a switch statement. For each case in the switch, calculate and return some next state.
```js {4-7,10-13} function reducer(state, action) { switch (action.type) { case 'incremented_age': { return { name: state.name, age: state.age + 1 }; } case 'changed_name': { return { name: action.nextName, age: state.age }; } } throw Error('Unknown action: ' + action.type); }
Actions can have any shape. By convention, it's common to pass objects with a `type` property identifying the action. It should include the minimal necessary information that the reducer needs to compute the next state.
```js {5,9-12}
function Form() {
const [state, dispatch] = useReducer(reducer, { name: 'Taylor', age: 42 });
function handleButtonClick() {
dispatch({ type: 'incremented_age' });
}
function handleInputChange(e) {
dispatch({
type: 'changed_name',
nextName: e.target.value
});
}
// ...
The action type names are local to your component. Each action describes a single interaction, even if that leads to multiple changes in data. The shape of the state is arbitrary, but usually it'll be an object or an array.
Read extracting state logic into a reducer to learn more.
[!WARNING]
State is read-only. Don't modify any objects or arrays in state:
```js {4,5} function reducer(state, action) { switch (action.type) { case 'incremented_age': { // 🚩 Don't mutate an object in state like this: state.age = state.age + 1; return state; }
>
> Instead, always return new objects from your reducer:
>
```js {4-8}
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
// ✅ Instead, return a new object
return {
...state,
age: state.age + 1
};
}
Read updating objects in state and updating arrays in state to learn more.
Form (object)
In this example, the reducer manages a state object with two fields: name and age.
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'incremented_age': {
return {
name: state.name,
age: state.age + 1
};
}
case 'changed_name': {
return {
name: action.nextName,
age: state.age
};
}
}
throw Error('Unknown action: ' + action.type);
}
const initialState = { name: 'Taylor', age: 42 };
export default function Form() {
const [state, dispatch] = useReducer(reducer, initialState);
function handleButtonClick() {
dispatch({ type: 'incremented_age' });
}
function handleInputChange(e) {
dispatch({
type: 'changed_name',
nextName: e.target.value
});
}
return (
<>
<input
value={state.name}
onChange={handleInputChange}
/>
<button onClick={handleButtonClick}>
Increment age
</button>
<p>Hello, {state.name}. You are {state.age}.</p>
</>
);
}
button { display: block; margin-top: 10px; }
Todo list (array)
In this example, the reducer manages an array of tasks. The array needs to be updated without mutation.
```js src/App.js import { useReducer } from 'react'; import AddTask from './AddTask.js'; import TaskList from './TaskList.js';
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); } } }
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/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; }
Writing concise update logic with Immer
If updating arrays and objects without mutation feels tedious, you can use a library like Immer to reduce repetitive code. Immer lets you write concise code as if you were mutating objects, but under the hood it performs immutable updates:
```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); } } }
