
Learn how to combine React’s useActionState, useOptimistic, and useTransition to implement ordered, optimistic UI updates for a channel‑sidebar layout, handling saves, rollbacks, and seamless user interaction.
Aurora Scharff
November 17, 2026
Originally published on aurorascharff.no
Overlapping writes are a common thing to deal with on the web, and frameworks handle them differently, like React Router cancelling interrupted requests and stale revalidations, or Solid Router tracking pending submissions. In React, we can combine useActionState and useOptimistic.
In this post, we'll look at how these hooks work together in Huddle.
Huddle is a Slack-like team chat app with a workspace rail, a channel sidebar, and the current channel. Here is the workspace shell:
// app/(workspace)/layout.tsx
<WorkspaceRail />
<ChannelSidebar>
<WorkspaceNav />
<SearchButton />
<ChannelList />
</ChannelSidebar>
<main>{children}</main>
Huddle's sidebar starts with ChannelList, which loads the saved groups in a Server Component:
// features/channel/components/channel-list.tsx
export async function ChannelList() {
const { groups, userId } = await getCurrentChannelLayout();
return <ChannelNav groups={groups} key={userId} />;
}
Those groups become the initial state for the ChannelNav Client Component, where the list and its interactions live:
// features/channel/components/channel-nav.tsx
"use client";
export function ChannelNav({ groups }: { groups: LayoutGroup[] }) {
// ...drag channels and create, rename, delete, or reorder groups...
return (
<nav aria-label="Channels">
{groups.map(group => (
<div key={group.name}>
<p>{group.name}</p>
{group.channels.map(channel => (
<ChannelLink channel={channel} key={channel.id} />
))}
</div>
))}
</nav>
);
}
We want the channel sidebar to update immediately when someone moves a channel or edits a group, while the layout changes save in order. A few posts and docs already cover combining useActionState and useOptimistic for that:
useOptimistic.useActionState docs now cover queued Actions and using both hooks together.To save the complete layout, we can add a Server Function. It writes the group positions and the channel positions inside them, simplified here from Huddle's transaction:
// features/channel/channel-actions.ts
"use server";
export async function saveChannelLayout(groups: LayoutGroup[]) {
const user = await verifyAuth();
for (const [position, group] of groups.entries()) {
await prisma.channelGroup.upsert({
create: { name: group.name, position, userId: user.id },
update: { position },
where: { userId_name: { name: group.name, userId: user.id } },
});
// ...write the group and position for the channels inside it...
}
// ...invalidate the cache...
}
With the Server Function in place, we can call saveChannelLayout inside a Transition in ChannelNav. Wrapping the call in useTransition sets isPending while the save runs, and the sidebar keeps accepting changes:
// features/channel/components/channel-nav.tsx
export function ChannelNav({ groups }: { groups: LayoutGroup[] }) {
const [isPending, startTransition] = useTransition();
function saveChange(nextGroups: LayoutGroup[]) {
startTransition(async () => {
await saveChannelLayout(nextGroups);
});
}
// ...render groups...
}
Next.js currently dispatches and awaits Server Actions one at a time, so these writes do not race in Huddle. Outside that queue, async work started directly inside a Transition can still finish out of order. The React docs describe this as out-of-order Transition updates and point to useActionState for common cases.
However, ChannelNav calculates nextGroups before the save enters the queue. If someone makes another change before the first save finishes, the second nextGroups is built from the layout as it was before either change. Next.js still writes the requests in order, so the later one lands last and drops the earlier change from the saved layout.
We could disable the controls while isPending is true, but that would make dragging and editing the sidebar feel slow. Instead, we can keep the sidebar interactive and make later changes build on the result of the save before them.
The useActionState hook stores the result of an Action and queues calls made through its dispatcher:
const [state, dispatchAction, isPending] = useActionState(
async (previousState, actionPayload) => {
// ...run the side effect...
return nextState;
},
initialState
);
If we dispatch several changes, React waits for one callback to finish before using its result in the next. We can await the save inside the callback, and isPending remains true until all the saves have finished.
To build a change on top of the previous save, saveChannelLayout needs the previous groups and a LayoutChange describing what happened. We can extract the layout update into a reducer:
// features/channel/utils/channel-layout-reducer.ts
export function channelLayoutReducer(
groups: LayoutGroup[],
change: LayoutChange
): LayoutGroup[] {
switch (change.type) {
case "move": {
const next = groups.map(group => ({
...group,
channels: group.channels.filter(
channel => channel.id !== change.channelId
),
}));
const moved = groups
.flatMap(group => group.channels)
.find(channel => channel.id === change.channelId);
const target = next.find(group => group.name === change.toGroup);
if (!moved || !target) return groups;
const index = Math.max(
0,
Math.min(change.toIndex, target.channels.length)
);
target.channels.splice(index, 0, moved);
return next;
}
case "addGroup": {
// ...return the layout with the new group, keeping Channels last...
}
case "renameGroup": {
// ...validate the name and return the renamed group...
}
case "deleteGroup": {
// ...return the layout with its channels moved to Channels...
}
case "moveGroup": {
// ...return the layout with the group moved up or down...
}
default:
return groups;
}
}
Inside the reducer, the move case removes a channel from its current group and inserts it into the target without changing the input. The other cases handle changes to the groups themselves. Now we can use channelLayoutReducer inside saveChannelLayout to calculate the layout we write:
// features/channel/channel-actions.ts
"use server";
import {
channelLayoutReducer,
type LayoutChange,
type LayoutGroup,
} from "@/features/channel/utils/channel-layout-reducer";
// ...database, cache, and auth imports...
export async function saveChannelLayout(
groups: LayoutGroup[],
change: LayoutChange
): Promise<LayoutGroup[]> {
await verifyAuth();
const next = channelLayoutReducer(groups, change);
// ...write next with the same upserts as above...
return next;
}
Once the write succeeds, the returned layout becomes the state for the next queued update. Back in ChannelNav, let's pass saveChannelLayout to useActionState:
// features/channel/components/channel-nav.tsx
"use client";
import { startTransition, useActionState } from "react";
// ...app imports...
export function ChannelNav({
groups: initialGroups,
}: {
groups: LayoutGroup[];
}) {
const [groups, dispatch] = useActionState(saveChannelLayout, initialGroups);
function runChange(change: LayoutChange) {
startTransition(() => {
dispatch(change);
});
}
// ...render groups...
}
React starts a Transition automatically for Action props such as <form action>. Huddle dispatches changes from drag and menu handlers, so we call startTransition explicitly inside runChange. When someone makes another change, React waits for the previous save and passes its returned layout into saveChannelLayout. The channelLayoutReducer applies the new LayoutChange to that layout.
The saves are ordered now, but the sidebar renders groups, which only updates after the Server Function finishes. Moving a channel would wait for the database write before appearing in the sidebar.
We can use useOptimistic to show temporary state while an Action is pending:
const [optimisticState, addOptimistic] = useOptimistic(
state,
(currentState, optimisticValue) => {
return nextState;
}
);
The first argument is the confirmed state. When we call addOptimistic, React passes the current optimistic state and the new value to the update function. Its return value is shown while the Action is pending. If the confirmed state changes in the meantime, React applies the update function again on top of it.
In Huddle, the confirmed state is groups, and the optimistic value is a LayoutChange. The channelLayoutReducer already accepts those two values, so let's pass it to useOptimistic in ChannelNav:
// features/channel/components/channel-nav.tsx
"use client";
import { startTransition, useActionState, useOptimistic } from "react";
// ...app imports...
export function ChannelNav({
groups: initialGroups,
}: {
groups: LayoutGroup[];
}) {
const [groups, dispatch] = useActionState(saveChannelLayout, initialGroups);
const [optimisticGroups, addOptimistic] = useOptimistic(
groups,
channelLayoutReducer
);
function runChange(change: LayoutChange) {
startTransition(() => {
addOptimistic(change);
dispatch(change);
});
}
// ...render optimisticGroups...
}
When runChange fires, the sidebar renders optimisticGroups immediately while dispatch saves the change. Once the save finishes, groups catches up to the layout already on screen.
An optimistic change can still fail to save. We want to let the user know and return the sidebar to the last layout that did save.
We can handle both inside the callback passed to useActionState. If saveChannelLayout throws, let's show a toast and return the previous groups passed into the callback:
// features/channel/components/channel-nav.tsx
"use client";
import { toast } from "sonner";
// ...app imports...
export function ChannelNav({
groups: initialGroups,
}: {
groups: LayoutGroup[];
}) {
const [groups, dispatch] = useActionState(
async (previousGroups: LayoutGroup[], change: LayoutChange) => {
try {
return await saveChannelLayout(previousGroups, change);
} catch {
toast.error("Could not save channel layout. Try again.");
return previousGroups;
}
},
initialGroups
);
// ...add useOptimistic and render optimisticGroups as above...
}
While the Action is pending, useOptimistic keeps the changed layout on screen. Once the Action finishes, React discards that temporary state and renders the confirmed groups from useActionState. After an error, those are still the groups from the last successful save, so the sidebar moves back without a reverse LayoutChange.
ChannelNavHere is the sidebar with the queue, the optimistic layout, and the rollback wired in. The drag and menu handlers go through runChange, and the render reads optimisticGroups:
// features/channel/components/channel-nav.tsx
"use client";
import { startTransition, useActionState, useOptimistic } from "react";
import { toast } from "sonner";
import { channelLayoutReducer } from "@/features/channel/utils/channel-layout-reducer";
// ...app imports...
export function ChannelNav({
groups: initialGroups,
}: {
groups: LayoutGroup[];
}) {
const [groups, dispatch] = useActionState(
async (previousGroups: LayoutGroup[], change: LayoutChange) => {
try {
return await saveChannelLayout(previousGroups, change);
} catch {
toast.error("Could not save channel layout. Try again.");
return previousGroups;
}
},
initialGroups
);
const [optimisticGroups, addOptimistic] = useOptimistic(
groups,
channelLayoutReducer
);
function runChange(change: LayoutChange) {
startTransition(() => {
addOptimistic(change);
dispatch(change);
});
}
return (
<nav aria-label="Channels">
{optimisticGroups.map(group => (
<div key={group.name}>
<p>{group.name}</p>
{/* ...drag handlers and the group menu call runChange... */}
{group.channels.map(channel => (
<ChannelLink channel={channel} key={channel.id} />
))}
</div>
))}
</nav>
);
}
This way, the sidebar moves the moment someone drops a channel, and the saves still run in the order the changes were made. If one of them fails, the sidebar goes back to the last layout the server confirmed.
What I like about this pattern is that Server Components continue to own the data. We only add enough client state to coordinate the interaction, then let the server result take over when the Action finishes.
Sources:
Ready to prove your React skills?
Get certified in ReactKeep learning React. Then get certified when you are ready.

How to Make a Useful Open Source Contribution
Learn how to make useful open source contributions by identifying reproducible problems, testing and documenting fixes, preparing clear pull requests, and working constructively with maintainers through review.
Aurora Scharff

Debugging Suspense with the React Suspense Panel
The Suspense panel in React Developer Tools shows which boundary suspended, what it was waiting for, and the order your page revealed its content.
Aurora Scharff

What's New in React 19.3
Explore what's new in React 19.3, including stable View Transitions, Fragment Refs, browser-only rendering, Trusted Types, and RSC updates.
Aurora Scharff