C.W.K.
Stream
Lesson 07 of 08 · published

Optimistic Update

~20 min · useOptimistic, instant UI

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

"Optimistic" 을 declarative 로

useOptimistic 이 server confirm 전에 action 의 expected outcome 보여주게 해줘. Hook 이 임시 "가짜" state 줘서 action fail 시 자동으로 revert.

모양

const [optimistic, addOptimistic] = useOptimistic(realState, reducer). 변경과 함께 addOptimistic 호출, 그 다음 action 실행. Optimistic state 가 action resolve + cache revalidate 까지 hold.

이게 빛나는 pattern

  • Like, heart, favorite — 즉각 feedback 이 essential 하게 느껴짐.
  • Round-trip > 100ms 인 toggle.
  • List 에 item 추가 (sending… indicator 와 함께).

Code

Optimistic todo list·tsx
'use client';
import { useOptimistic } from 'react';
import { addTodo } from '@/app/actions';

type Todo = { id: string; text: string; sending?: boolean };

export function TodoList({ todos }: { todos: Todo[] }) {
  const [optimistic, addOptimistic] = useOptimistic(
    todos,
    (state, newText: string) => [
      ...state,
      { id: crypto.randomUUID(), text: newText, sending: true },
    ]
  );

  async function handleSubmit(formData: FormData) {
    const text = formData.get('text') as string;
    addOptimistic(text);          // 즉시 visible
    await addTodo(formData);      // background
  }

  return (
    <>
      <ul>
        {optimistic.map(t => (
          <li key={t.id} style={{ opacity: t.sending ? 0.5 : 1 }}>
            {t.text}{t.sending && <span className="ml-2 text-xs">saving&hellip;</span>}
          </li>
        ))}
      </ul>
      <form action={handleSubmit}>
        <input name="text" required />
        <button>Add</button>
      </form>
    </>
  );
}

External links

Exercise

App 의 like-button 또는 favorite-toggle 에 optimistic UI 추가. 의도적으로 throttled network 에서 클릭이 즉각으로 느껴지는지 보여줘.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.