useOptimistic
useOptimistic is a React Hook that lets you optimistically update the UI.
const [optimisticState, setOptimistic] = useOptimistic(value, reducer?);
Reference
useOptimistic(value, reducer?)
Call useOptimistic at the top level of your component to create optimistic state for a value.
import { useOptimistic } from 'react';
function MyComponent({name, todos}) {
const [optimisticAge, setOptimisticAge] = useOptimistic(28);
const [optimisticName, setOptimisticName] = useOptimistic(name);
const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, todoReducer);
// ...
}
Parameters
value: The value returned when there are no pending Actions.- optional
reducer(currentState, action): The reducer function that specifies how the optimistic state gets updated. It must be pure, should take the current state and reducer action arguments, and should return the next optimistic state.
Returns
useOptimistic returns an array with exactly two values:
optimisticState: The current optimistic state. It is equal tovalueunless an Action is pending, in which case it is equal to the state returned byreducer(or the value passed to the set function if noreducerwas provided).- The
setfunction that lets you update the optimistic state to a different value inside an Action.
set functions, like setOptimistic(optimisticState)
The set function returned by useOptimistic lets you update the state for the duration of an Action. You can pass the next state directly, or a function that calculates it from the previous state:
const [optimisticLike, setOptimisticLike] = useOptimistic(false);
const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs);
function handleClick() {
startTransition(async () => {
setOptimisticLike(true);
setOptimisticSubs(a => a + 1);
await saveChanges();
});
}
Parameters
optimisticState: The value that you want the optimistic state to be during an Action. If you provided areducertouseOptimistic, this value will be passed as the second argument to your reducer. It can be a value of any type.- If you pass a function as
optimisticState, it will be treated as an updater function. It must be pure, should take the pending state as its only argument, and should return the next optimistic state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying the queued updaters to the previous state similar touseStateupdaters.
- If you pass a function as
Returns
set functions do not have a return value.
Caveats
- The
setfunction must be called inside an Action. If you call the setter outside an Action, React will show a warning and the optimistic state will briefly render.
[!INFO]
How optimistic state works
useOptimisticlets you show a temporary value while an Action is in progress:
const [value, setValue] = useState('a');
const [optimistic, setOptimistic] = useOptimistic(value);
startTransition(async () => {
setOptimistic('b');
const newValue = await saveChanges('b');
setValue(newValue);
});
When the setter is called inside an Action,
useOptimisticwill trigger a re-render to show that state while the Action is in progress. Otherwise, thevaluepassed touseOptimisticis returned.This state is called the "optimistic" because it is used to immediately present the user with the result of performing an Action, even though the Action actually takes time to complete.
How the update flows
Update immediately: When
setOptimistic('b')is called, React immediately renders with'b'.(Optional) await in Action: If you await in the Action, React continues showing
'b'.Transition scheduled:
setValue(newValue)schedules an update to the real state.(Optional) wait for Suspense: If
newValuesuspends, React continues showing'b'.Single render commit: Finally, the
newValuecommits forvalueandoptimistic.There's no extra render to "clear" the optimistic state. The optimistic and real state converge in the same render when the Transition completes.
[!NOTE]
Optimistic state is temporary
Optimistic state only renders while an Action is in progress, otherwise
valueis rendered.If
saveChangesreturned'c', then bothvalueandoptimisticwill be'c', not'b'.How the final state is determined
The
valueargument touseOptimisticdetermines what displays after the Action finishes. How this works depends on the pattern you use:
Hardcoded values like
useOptimistic(false): After the Action,stateis stillfalse, so the UI showsfalse. This is useful for pending states where you always start fromfalse.Props or state passed in like
useOptimistic(isLiked): If the parent updatesisLikedduring the Action, the new value is used after the Action completes. This is how the UI reflects the result of the Action.Reducer pattern like
useOptimistic(items, fn): Ifitemschanges while the Action is pending, React re-runs yourreducerwith the newitemsto recalculate the state. This keeps your optimistic additions on top of the latest data.What happens when the Action fails
If the Action throws an error, the Transition still ends, and React renders with whatever
valuecurrently is. Since the parent typically only updatesvalueon success, a failure meansvaluehasn't changed, so the UI shows what it showed before the optimistic update. You can catch the error to show a message to the user.
Usage
Adding optimistic state to a component
Call useOptimistic at the top level of your component to declare one or more optimistic states.
```js [[1, 4, "age"], [1, 5, "name"], [1, 6, "todos"], [2, 4, "optimisticAge"], [2, 5, "optimisticName"], [2, 6, "optimisticTodos"], [3, 4, "setOptimisticAge"], [3, 5, "setOptimisticName"], [3, 6, "setOptimisticTodos"], [4, 6, "reducer"]] import { useOptimistic } from 'react';
function MyComponent({age, name, todos}) { const [optimisticAge, setOptimisticAge] = useOptimistic(age); const [optimisticName, setOptimisticName] = useOptimistic(name); const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, reducer); // ...
`useOptimistic` returns an array with exactly two items:
1. The <CodeStep step={2}>optimistic state</CodeStep>, initially set to the <CodeStep step={1}>value</CodeStep> provided.
2. The <CodeStep step={3}>set function</CodeStep> that lets you temporarily change the state during an [Action](reference/react/useTransition#functions-called-in-starttransition-are-called-actions).
* If a <CodeStep step={4}>reducer</CodeStep> is provided, it will run before returning the optimistic state.
To use the <CodeStep step={2}>optimistic state</CodeStep>, call the `set` function inside an Action.
Actions are functions called inside `startTransition`:
```js {3}
function onAgeChange(e) {
startTransition(async () => {
setOptimisticAge(42);
const newAge = await postAge(42);
setAge(newAge);
});
}
React will render the optimistic state 42 first while the age remains the current age. The Action waits for POST, and then renders the newAge for both age and optimisticAge.
See How optimistic state works for a deep dive.
[!NOTE]
When using Action props, you can call the set function without
startTransition:```js [[3, 2, "setOptimisticName"]] async function submitAction() { setOptimisticName('Taylor'); await updateName('Taylor'); }
>
> This works because Action props are already called inside `startTransition`.
>
> For an example, see: [Using optimistic state in Action props](#using-optimistic-state-in-action-props).
>
---
### Using optimistic state in Action props
In an [Action prop](/reference/react/useTransition#exposing-action-props-from-components), you can call the optimistic setter directly without `startTransition`.
This example sets optimistic state inside a `<form>` `submitAction` prop:
```js src/App.js
import { useState, startTransition } from 'react';
import EditName from './EditName';
export default function App() {
const [name, setName] = useState('Alice');
return <EditName name={name} action={setName} />;
}
```js src/EditName.js active import { useOptimistic, startTransition } from 'react'; import { updateName } from './actions.js';
export default function EditName({ name, action }) { const [optimisticName, setOptimisticName] = useOptimistic(name);
async function submitAction(formData) { const newName = formData.get('name'); setOptimisticName(newName);
const updatedName = await updateName(newName); startTransition(() => { action(updatedName); }) }
return (
); }
```js src/actions.js hidden
export async function updateName(name) {
await new Promise((res) => setTimeout(res, 1000));
return name;
}
In this example, when the user submits the form, the optimisticName updates immediately to show the newName optimistically while the server request is in progress. When the request completes, name and optimisticName are rendered with the actual updatedName from the response.
[!INFO]
Why doesn't this need
startTransition?By convention, props called inside
startTransitionare named with "Action".Since
submitActionis named with "Action", you know it's already called insidestartTransition.See Exposing
actionprop from components for the Action prop pattern.
Adding optimistic state to Action props
When creating an Action prop, you can add useOptimistic to show immediate feedback.
Here's a button that shows "Submitting..." while the action is pending:
```js src/App.js import { useState, startTransition } from 'react'; import Button from './Button'; import { submitForm } from './actions.js';
export default function App() { const [count, setCount] = useState(0); return (
Submitted {count}!
}
```js src/Button.js active
import { useOptimistic, startTransition } from 'react';
export default function Button({ action, children }) {
const [isPending, setIsPending] = useOptimistic(false);
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
setIsPending(true);
await action();
});
}}
>
{isPending ? 'Submitting...' : children}
</button>
);
}
```js src/actions.js hidden export async function submitForm() { await new Promise((res) => setTimeout(res, 1000)); }
When the button is clicked, `setIsPending(true)` uses optimistic state to immediately show "Submitting..." and disable the button. When the Action is done, `isPending` is rendered as `false` automatically.
This pattern automatically shows a pending state however `action` prop is used with `Button`:
```js
// Show pending state for a state update
<Button action={() => { setState(c => c + 1) }} />
// Show pending state for a navigation
<Button action={() => { navigate('/done') }} />
// Show pending state for a POST
<Button action={async () => { await fetch(/* ... */) }} />
// Show pending state for any combination
<Button action={async () => {
setState(c => c + 1);
await fetch(/* ... */);
navigate('/done');
}} />
The pending state will be shown until everything in the action prop is finished.
[!NOTE]
You can also use
useTransitionto get pending state viaisPending.The difference is that
useTransitiongives you thestartTransitionfunction, whileuseOptimisticworks with any Transition. Use whichever fits your component's needs.
Updating props or state optimistically
You can wrap props or state in useOptimistic to update it immediately while an Action is in progress.
In this example, LikeButton receives isLiked as a prop and immediately toggles it when clicked:
```js src/App.js import { useState, useOptimistic, startTransition } from 'react'; import { toggleLike } from './actions.js';
export default function App() { const [isLiked, setIsLiked] = useState(false); const [optimisticIsLiked, setOptimisticIsLiked] = useOptimistic(isLiked);
function handleClick() { startTransition(async () => { const newValue = !optimisticIsLiked console.log('⏳ setting optimistic state: ' + newValue);
setOptimisticIsLiked(newValue); const updatedValue = await toggleLike(newValue);
startTransition(() => { console.log('⏳ setting real state: ' + updatedValue ); setIsLiked(updatedValue); }); }); }
if (optimisticIsLiked !== isLiked) { console.log('✅ rendering optimistic state: ' + optimisticIsLiked); } else { console.log('✅ rendering real value: ' + optimisticIsLiked); }
return ( ); }
```js src/actions.js hidden
export async function toggleLike(value) {
return await new Promise((res) => setTimeout(() => res(value), 1000));
// In a real app, this would update the server
}
```js src/index.js hidden import React from 'react'; import {createRoot} from 'react-dom/client'; import './styles.css';
import App from './App';
const root = createRoot(document.getElementById('root'));
// Not using StrictMode so double render logs are not shown.
root.render(
When the button is clicked, setOptimisticIsLiked immediately updates the displayed state to show the heart as liked. Meanwhile, await toggleLike runs in the background. When the await completes, setIsLiked parent updates the "real" isLiked state, and the optimistic state is rendered to match this new value.
[!NOTE]
This example reads from
optimisticIsLikedto calculate the next value. This works when the base state won't change, but if the base state might change while your Action is pending, you may want to use a state updater or the reducer.See Updating state based on the current state for an example.
Updating multiple values together
When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent.
Here's a follow button that updates both the follow state and follower count:
```js src/App.js import { useState, startTransition } from 'react'; import { followUser, unfollowUser } from './actions.js'; import FollowButton from './FollowButton';
export default function App() { const [user, setUser] = useState({ name: 'React', isFollowing: false, followerCount: 10500 });
async function followAction(shouldFollow) { if (shouldFollow) { await followUser(user.name); } else { await unfollowUser(user.name); } startTransition(() => { setUser(current => ({ ...current, isFollowing: shouldFollow, followerCount: current.followerCount + (shouldFollow ? 1 : -1) })); }); }
