0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 강의

낙관적 UI 업데이트

서버 확인 전에 사용자에게 즉각적인 피드백을 제공하도록 Server Actions와 함께 낙관적 UI 패턴을 구현합니다.

낙관적 UI 업데이트은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“낙관적 UI 업데이트” 강의는 무료인가요?

네 — “낙관적 UI 업데이트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 3개의 강의가 포함되어 있습니다.

“낙관적 UI 업데이트”에서 뭘 배우나요?

서버 확인 전에 사용자에게 즉각적인 피드백을 제공하도록 Server Actions와 함께 낙관적 UI 패턴을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.

“낙관적 UI 업데이트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 낙관적 UI 업데이트
  2. 액션을 활용한 파일 업로드
  3. Server Actions의 검증과 오류 처리
← Next.js 15 Fullstack (App Router + Server Actions)(으)로 돌아가기