typescriptintermediate
useOptimistic for Instant UI Updates
Use useOptimistic hook for instant UI feedback while server actions process in the background.
typescriptPress ⌘/Ctrl + Shift + C to copy
'use client';
import { useOptimistic } from 'react';
interface Todo {
id: string;
text: string;
completed: boolean;
}
async function toggleTodo(id: string) {
'use server';
// Update in database...
await new Promise((r) => setTimeout(r, 1000));
}
export default function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addOptimistic] = useOptimistic(
todos,
(state: Todo[], updatedId: string) =>
state.map((todo) =>
todo.id === updatedId
? { ...todo, completed: !todo.completed }
: todo
)
);
async function handleToggle(id: string) {
addOptimistic(id); // Instant UI update
await toggleTodo(id); // Server update in background
}
return (
<ul>
{optimisticTodos.map((todo) => (
<li key={todo.id} className="flex items-center gap-2">
<input
type="checkbox"
checked={todo.completed}
onChange={() => handleToggle(todo.id)}
/>
<span className={todo.completed ? 'line-through text-gray-400' : ''}>
{todo.text}
</span>
</li>
))}
</ul>
);
}Use Cases
- todo lists
- like buttons
- instant feedback patterns
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms
typescriptintermediate
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
#nextjs#server-actions
typescriptadvanced
Form with Server Action Validation
Build forms using Next.js server actions with server-side validation, error handling, and useActionState.
Best for: Contact form submissions
#nextjs#forms
typescriptbeginner
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
Best for: form submissions
#nextjs#server-actions