0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

乐观用户界面更新

使用服务器操作实现乐观用户界面模式,在服务器确认前向用户提供即时反馈

乐观用户界面更新 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

Instant Feedback with Optimistic UI

Imagine clicking 'Like' on a post. Does it update instantly, or do you wait for a spinner?

Optimistic UI is a technique where the user interface updates immediately after an action, *before* the server confirms it. This gives users instant feedback and makes your app feel much faster and more responsive.

How Optimistic UI Works

The process is simple:

  • User Action: The user performs an action (e.g., submitting a form).
  • Instant UI Update: Your UI immediately updates to reflect the *expected* outcome.
  • Server Action: In the background, a server request (like a Next.js Server Action) is sent to perform the actual operation.
  • Reconciliation: If the server action succeeds, the UI stays as is. If it fails, the UI reverts to its previous state.

This creates a smooth, uninterrupted user experience.

Next.js 15 & useOptimistic

Next.js 15, powered by React, provides the useOptimistic hook to make implementing optimistic UI updates straightforward.

This hook is specifically designed to manage a temporary, speculative state that anticipates the result of an asynchronous operation (like a Server Action) before the final server response is received.

Understanding useOptimistic Syntax

The useOptimistic hook has a simple signature:

const [optimisticState, addOptimistic] = useOptimistic(state, updater);
  • state: The actual, authoritative state (e.g., data fetched from the server).
  • updater: A function that takes the current state and a payload, returning the new optimistic state.
  • optimisticState: The state that your UI should currently display. It will be either the actual state or the optimistically updated state.
  • addOptimistic: A function you call with a payload to trigger an optimistic update.

Code Demo: Basic Task List

Let's start with a simple client component that manages a list of tasks using standard React useState. Run this to see how it works normally.

'use client';

import { useState } from 'react';

export default function TaskList() {
  const [tasks, setTasks] = useState([
    { id: 1, text: 'Plan lesson' },
    { id: 2, text: 'Review code' }
  ]);
  const [input, setInput] = useState('');

  const handleAddTask = () => {
    if (input.trim() === '') return;
    const newTask = { id: Date.now(), text: input };
    setTasks((prev) => [...prev, newTask]);
    setInput('');
  };

  return (
    <div>
      <h3>My Daily Tasks</h3>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>{task.text}</li>
        ))}
      </ul>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Add new task..."
      />
      <button onClick={handleAddTask}>Add Task</button>
    </div>
  );
}

Code Demo: Adding Optimistic Updates

Now, let's enhance our task list with useOptimistic. When you add a task, it will appear instantly with a ' (pending...)' label, even before our simulated server action finishes.

'use client';

import { useState, useOptimistic } from 'react';

export default function OptimisticTaskList() {
  const [tasks, setTasks] = useState([
    { id: 1, text: 'Plan lesson' },
    { id: 2, text: 'Review code' }
  ]);
  const [input, setInput] = useState('');

  // useOptimistic hook setup
  const [optimisticTasks, addOptimisticTask] = useOptimistic(
    tasks, // The actual source of truth
    (currentTasks, newTaskText) => [ // Updater function
      ...currentTasks,
      { id: Date.now(), text: newTaskText + ' (pending...)' }
    ]
  );

  // Simulate a server action with a delay
  async function simulateServerAction(text) {
    await new Promise(resolve => setTimeout(resolve, 1500));
    // In a real Next.js app, this would be a Server Action
    // that updates a database and triggers revalidation.
    // Here, we simulate the *result* of that revalidation
    // by updating the actual 'tasks' state after the delay.
    const newServerTask = { id: Date.now(), text: text };
    setTasks((prev) => [...prev, newServerTask]);
  }

  async function handleSubmit(event) {
    event.preventDefault();
    if (input.trim() === '') return;
    const taskText = input;
    setInput(''); // Clear input immediately

    // Step 1: Optimistically update the UI
    addOptimisticTask(taskText);

    // Step 2: Call the 'server action' (simulated)
    await simulateServerAction(taskText);
  }

  return (
    <div>
      <h3>Optimistic Tasks</h3>
      <ul>
        {optimisticTasks.map(task => (
          <li key={task.id}>{task.text}</li>
        ))}
      </ul>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Add new task..."
        />
        <button type="submit">Add Task</button>
      </form>
    </div>
  );
}

Connecting to Real Server Actions

In a live Next.js application, the simulateServerAction function from our example would be replaced by an actual Next.js Server Action.

A Server Action would typically:

  1. Update a database or external service.
  2. Call revalidatePath() or revalidateTag() to tell Next.js to fetch the latest data.

When Next.js revalidates, your component will re-render with the true, confirmed state from the server, automatically replacing the optimistic state.

Handling Errors and Reversion

What happens if the server action fails? This is where optimistic UI truly shines.

  • If the server action returns an error, Next.js's revalidation will fetch the *actual* data from the server.
  • Since the server didn't confirm the change, the UI will automatically revert to the previous correct state.

While the UI reverts, it's crucial to provide user feedback, like a toast notification, explaining why the action failed.

Best Practices for Optimistic UI

To make the most of optimistic updates:

  • Keep it Simple: Best for simple, predictable actions like toggling a 'like' or adding an item.
  • Predictable Outcomes: Only use when you're confident the server action will succeed.
  • Error Feedback: Always have a robust error handling strategy to inform users if an action fails.
  • Avoid Complex Logic: Don't use for actions with complex server-side validation or side effects that might lead to unexpected UI states.

Check Your Understanding

Which of the following are key benefits of implementing Optimistic UI updates?

Recap: Enhance User Experience

You've learned about Optimistic UI, a powerful technique to make your Next.js applications feel incredibly fast and responsive.

  • By using the useOptimistic hook, you can update the UI instantly, anticipating server responses.
  • This approach, combined with Next.js Server Actions and revalidation, ensures the UI eventually reflects the true server state, even in case of errors.

Mastering optimistic updates is a great step towards building highly engaging user experiences!

常见问题解答

「乐观用户界面更新」课时是免费的吗?

是的 — 「乐观用户界面更新」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 3 节课。

「乐观用户界面更新」这节课中我会学到什么?

使用服务器操作实现乐观用户界面模式,在服务器确认前向用户提供即时反馈 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。

「乐观用户界面更新」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 乐观用户界面更新
  2. 使用操作上传文件
  3. 服务器操作中的验证与错误处理
← 返回 Next.js 15 Fullstack (App Router + Server Actions)