Sub topic 2
Actions and transitions: the context useOptimistic works in
This chapter assumes you know React function components, useState, props, async/await, and how to send data to a server with fetch or a server function. It covers the React 19 mechanism that useOptimistic depends on. The hook itself comes in the next chapter. Here you learn what an Action is, how transitions track one, and why an optimistic update has to run inside one.
Why this comes first
useOptimistic does not work as a standalone replacement for useState. It shows a temporary value for as long as some asynchronous work is in progress. React needs a way to know when that work starts and when it ends, and Actions and transitions provide it.
If you call the optimistic setter at the wrong place, React has no "work in progress" to tie the value to. It logs a warning, and the update does not behave as intended. Understanding the context removes that confusion.
Transitions: marking updates as non-urgent
A transition is a state update that React treats as non-urgent. React can keep the current UI responsive while it prepares the result of the transition. You mark updates this way with startTransition, or with the useTransition hook, which also tells you whether a transition is running.
import { useState, useTransition } from "react";
function Tabs() {
const [tab, setTab] = useState("home");
const [isPending, startTransition] = useTransition();
function select(next) {
startTransition(() => {
setTab(next);
});
}
return (
<>
<button onClick={() => select("home")}>Home</button>
<button onClick={() => select("reports")}>Reports</button>
{isPending && <p>Loading...</p>}
<p>Current tab: {tab}</p>
</>
);
}isPending is true from the moment the transition starts until React has finished rendering its result. Before React 19, the function passed to startTransition had to be synchronous. That limit is what changed.
Actions: transitions that can be async
In React 19, the function you pass to startTransition can be async. React calls such a function an Action. By convention, an Action is any function that runs inside a transition and performs a state change, often with a request to a server.
React tracks the promise the function returns. The transition stays pending until that promise settles. This gives you several things without writing extra state:
- A pending flag.
isPendingstaystruefor the whole request, not only for the first render. - Ordering of updates. State updates in the Action are held together as one transition.
- Error propagation. If the Action throws, the error goes to the nearest error boundary unless you catch it.
- A temporary scope. Optimistic values live for exactly as long as the Action runs.
The last point is what useOptimistic uses.
import { useState, useTransition } from "react";
function RenameForm({ currentName, saveName }) {
const [name, setName] = useState(currentName);
const [isPending, startTransition] = useTransition();
function handleClick() {
startTransition(async () => {
await saveName(name);
});
}
return (
<>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={handleClick} disabled={isPending}>
{isPending ? "Saving..." : "Save"}
</button>
</>
);
}Here saveName is a function that returns a promise. The button is disabled while the request is in flight, and you did not write an isSaving state variable.
The lifecycle of an Action
The sequence below shows what happens when a user triggers an Action. The optimistic value exists only between the start of the Action and the moment it settles.
The gotcha: updates after an await
A transition marks state updates that run synchronously while the function executes. React does not keep that marking across an await. Code that runs after the await is no longer inside the transition scope. A state update there is treated as an ordinary update.
If you want an update after an await to count as part of the transition, wrap it in another startTransition.
import { useState, startTransition } from "react";
function Profile({ fetchProfile }) {
const [profile, setProfile] = useState(null);
function handleClick() {
startTransition(async () => {
const data = await fetchProfile();
// Without the inner startTransition, this update is not part of the transition.
startTransition(() => {
setProfile(data);
});
});
}
return (
<>
<button onClick={handleClick}>Load profile</button>
{profile && <p>{profile.name}</p>}
</>
);
}The gotcha is not tied to useOptimistic, but it affects how you structure Actions. Call the optimistic setter before the first await. At that point you are still inside the transition scope.
Form actions
Actions also come from forms. In React 19 you can pass a function to a form's action prop instead of an onSubmit handler. React calls that function with a FormData object when the form is submitted, and it runs the function inside a transition. The function is an Action even though you never wrote startTransition.
function Subscribe({ subscribe }) {
async function formAction(formData) {
const email = formData.get("email");
await subscribe(email);
}
return (
<form action={formAction}>
<input type="email" name="email" required />
<button type="submit">Subscribe</button>
</form>
);
}Some differences from onSubmit are worth knowing:
- You do not call
event.preventDefault(). React handles the submission. - The input values arrive as
FormData, so the inputs can be uncontrolled and need nouseState. - When the Action finishes successfully, React resets uncontrolled form fields.
- The form stays in a pending state while the returned promise is unsettled. The
useFormStatushook, called from a component inside the form, reads that state.
Form actions are the most common home for optimistic updates, because a form submission is the typical "send something, then wait" interaction. A later chapter builds a full example around one.
Where useOptimistic fits
With the context in place, here is a first look at the hook. The next chapter explains its signature in detail. For now, only the position of the setter call matters.
import { startTransition, useOptimistic } from "react";
function LikeButton({ liked, saveLiked }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function handleClick() {
startTransition(async () => {
setOptimisticLiked(!liked); // before the first await
await saveLiked(!liked);
});
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}The order of events:
- The click starts a transition with an async function. This is the Action.
setOptimisticLiked(!liked)runs immediately. The button changes label on the next render, before the server has replied.await saveLiked(!liked)keeps the Action open while the request runs.- When the promise settles, the Action ends. React drops the optimistic value and shows the real
likedprop again.
Step 4 is why the optimistic state exists only during the Action. If the parent updated liked after a successful save, the button shows the new real value. If the request failed and liked did not change, the button shows the old value. Later chapters cover that revert in detail.
What happens outside an Action
Calling the optimistic setter from a plain event handler, an effect, or a timer does not give it an Action to belong to. In development, React warns that an optimistic update occurred outside a transition or Action.
function BadLikeButton({ liked, saveLiked }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
async function handleClick() {
setOptimisticLiked(!liked); // warning: not inside an Action
await saveLiked(!liked);
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}The fix is to wrap the body in startTransition(async () => { ... }), as in LikeButton above, or to move the code into a form action.
Common errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Calling the optimistic setter in a plain `async` handler | React warns, and the value is not tied to an Action | Wrap the work in `startTransition(async () => { ... })` or use a form action |
| Calling the setter after an `await` | The call is outside the transition scope | Move the setter before the first `await` |
| Setting real state after an `await` and expecting transition behavior | The update is treated as an ordinary update | Wrap it in a nested `startTransition` |
| Forgetting that an uncaught error in an Action reaches an error boundary | The component tree is replaced by the fallback UI | Catch errors in the Action when you want to show an inline message |
| Using `event.preventDefault()` habits with `action` | Unneeded, and `onSubmit` logic can conflict with `action` | Use either `action` or `onSubmit`, not both |
Summary of the working model
- A transition is a non-urgent state update.
startTransitionmarks one, anduseTransitionalso gives youisPending. - An Action is an async function run inside a transition. React keeps the transition pending until the function's promise settles.
- Form actions run as Actions automatically.
- State updates after an
awaitleave the transition scope unless you wrap them instartTransitionagain. useOptimisticties its temporary value to a running Action. Call its setter early in the Action, before anyawait.
Exercise
A developer writes this handler and sees a React warning in development: async function handleClick() { setOptimisticLiked(!liked); await saveLiked(!liked); }. What is wrong, and how do you fix it?
Show answer
The handler is not an Action, because it does not run inside a transition. The optimistic setter has no running Action to attach its temporary value to. Wrap the body in startTransition(async () => { setOptimisticLiked(!liked); await saveLiked(!liked); }), importing startTransition from react. Alternatively, move the logic into a function passed to a form's action prop.
Exercise
Inside startTransition(async () => { ... }), you call const data = await load(); and then setProfile(data);. Why might setProfile not behave as part of the transition, and what is the fix?
Show answer
React tracks transition scope only for code that runs synchronously before the first await. After the await, the call to setProfile runs as an ordinary update. Wrap it in a nested startTransition(() => { setProfile(data); }) to mark it as part of a transition.
Exercise
Why can a form that uses <form action={fn}> call an optimistic setter without any explicit startTransition?
Show answer
React runs the function passed to action inside a transition. That makes the function an Action, so the optimistic setter has a running Action to belong to. It should still be called before the first await in the function.