Communitygithub.com

React UI 模式

用於載入狀態、錯誤處理和資料擷取的現代 React UI 模式。適用於建構 UI 元件、處理非同步資料或管理 UI 狀態時。

React UI 模式 是什麼?

此技能提供了一套全面的 React 使用者介面模式,重點在於載入狀態、錯誤處理、按鈕狀態、空狀態以及表單提交等常見場景。其核心原則包括永不顯示過時 UI、始終向使用者呈現錯誤、使用樂觀更新來提升即時感、漸進式揭露內容以及優雅降級以處理部分資料。技能詳細說明了何時使用旋轉圖示與骨架螢幕的區別,並提供了清晰的決策樹來決定 UI 狀態的顯示邏輯。它強烈反對靜默吞沒錯誤,並要求所有非同步操作都必須有 onError 處理器,同時按鈕在非同步操作期間必須被停用。此技能適用於所有 React 專案,不論使用何種狀態管理或資料擷取庫,並能與 GraphQL、測試以及 Formik 等其他模式無縫整合。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/chriswiles/react-ui-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

React UI 模式 是做什麼的?

核心原則

  1. 永不顯示過時 UI - 僅在實際載入時顯示載入旋轉圖示
  2. 始終呈現錯誤 - 使用者必須知道何時發生錯誤
  3. 樂觀更新 - 讓 UI 感覺即時
  4. 漸進式揭露 - 內容隨著可用性逐步顯示
  5. 優雅降級 - 部分資料總比沒有資料好

載入狀態模式

黃金法則

僅在沒有資料可顯示時才顯示載入指示器。

// 正確 - 僅在沒有資料時顯示載入
const { data, loading, error } = useGetItemsQuery();

if (error) return <ErrorState error={error} onRetry={refetch} />;
if (loading && !data) return <LoadingState />;
if (!data?.items.length) return <EmptyState />;

return <ItemList items={data.items} />;
// 錯誤 - 即使有快取資料也顯示旋轉圖示
if (loading) return <LoadingState />; // 重新擷取時會閃爍!

載入狀態決策樹

是否有錯誤?
  → 是:顯示帶有重試選項的錯誤狀態
  → 否:繼續

是否正在載入且我們沒有資料?
  → 是:顯示載入指示器(旋轉圖示/骨架螢幕)
  → 否:繼續

我們是否有資料?
  → 有,且有項目:顯示資料
  → 有,但為空:顯示空狀態
  → 沒有:顯示載入(備用)

骨架螢幕與旋轉圖示

使用骨架螢幕時機使用旋轉圖示時機
已知內容形狀未知內容形狀
列表/卡片佈局模態框操作
初始頁面載入按鈕提交
內容佔位符內聯操作

錯誤處理模式

錯誤處理層級

1. 內聯錯誤(欄位層級)→ 表單驗證錯誤
2. Toast 通知 → 可復原錯誤,使用者可以重試
3. 錯誤橫幅 → 頁面層級錯誤,資料仍可部分使用
4. 完整錯誤畫面 → 不可復原,需要使用者操作

始終顯示錯誤

重要:切勿靜默吞沒錯誤。

// 正確 - 錯誤始終呈現給使用者
const [createItem, { loading }] = useCreateItemMutation({
  onCompleted: () => {
    toast.success({ title: '項目已建立' });
  },
  onError: (error) => {
    console.error('createItem 失敗:', error);
    toast.error({ title: '建立項目失敗' });
  },
});

// 錯誤 - 錯誤被靜默捕獲,使用者完全不知道
const [createItem] = useCreateItemMutation({
  onError: (error) => {
    console.error(error); // 使用者看不到任何東西!
  },
});

錯誤狀態元件模式

interface ErrorStateProps {
  error: Error;
  onRetry?: () => void;
  title?: string;
}

const ErrorState = ({ error, onRetry, title }: ErrorStateProps) => (
  <div className="error-state">
    <Icon name="exclamation-circle" />
    <h3>{title ?? '發生錯誤'}</h3>
    <p>{error.message}</p>
    {onRetry && (
      <Button onClick={onRetry}>重試</Button>
    )}
  </div>
);

按鈕狀態模式

按鈕載入狀態

<Button
  onClick={handleSubmit}
  isLoading={isSubmitting}
  disabled={!isValid || isSubmitting}
>
  提交
</Button>

操作期間停用

重要:非同步操作期間務必停用觸發器。

// 正確 - 載入時按鈕被停用
<Button
  disabled={isSubmitting}
  isLoading={isSubmitting}
  onClick={handleSubmit}
>
  提交
</Button>

// 錯誤 - 使用者可以點擊多次
<Button onClick={handleSubmit}>
  {isSubmitting ? '提交中...' : '提交'}
</Button>

空狀態

空狀態需求

每個列表/集合都必須有空狀態:

// 錯誤 - 沒有空狀態
return <FlatList data={items} />;

// 正確 - 明確的空狀態
return (
  <FlatList
    data={items}
    ListEmptyComponent={<EmptyState />}
  />
);

情境式空狀態

// 搜尋無結果
<EmptyState
  icon="search"
  title="找不到結果"
  description="嘗試不同的搜尋詞"
/>

// 列表尚無項目
<EmptyState
  icon="plus-circle"
  title="尚無項目"
  description="建立您的第一個項目"
  action={{ label: '建立項目', onClick: handleCreate }}
/>

表單提交模式

const MyForm = () => {
  const [submit, { loading }] = useSubmitMutation({
    onCompleted: handleSuccess,
    onError: handleError,
  });

  const handleSubmit = async () => {
    if (!isValid) {
      toast.error({ title: '請修正錯誤' });
      return;
    }
    await submit({ variables: { input: values } });
  };

  return (
    <form>
      <Input
        value={values.name}
        onChange={handleChange('name')}
        error={touched.name ? errors.name : undefined}
      />
      <Button
        type="submit"
        onClick={handleSubmit}
        disabled={!isValid || loading}
        isLoading={loading}
      >
        提交
      </Button>
    </form>
  );
};

反模式

載入狀態

// 錯誤 - 資料存在時顯示旋轉圖示(導致閃爍)
if (loading) return <Spinner />;

// 正確 - 僅在沒有資料時顯示載入
if (loading && !data) return <Spinner />;

錯誤處理

// 錯誤 - 錯誤被吞沒
try {
  await mutation();
} catch (e) {
  console.log(e); // 使用者完全不知道!
}

// 正確 - 錯誤被呈現
onError: (error) => {
  console.error('操作失敗:', error);
  toast.error({ title: '操作失敗' });
}

按鈕狀態

// 錯誤 - 提交期間按鈕未停用
<Button onClick={submit}>提交</Button>

// 正確 - 停用並顯示載入狀態
<Button onClick={submit} disabled={loading} isLoading={loading}>
  提交
</Button>

檢查清單

在完成任何 UI 元件之前:

UI 狀態:

  • 錯誤狀態已處理並呈現給使用者
  • 僅在沒有資料時顯示載入狀態
  • 集合已提供空狀態
  • 非同步操作期間按鈕已停用
  • 按鈕在適當情況下顯示載入指示器

資料與變更:

  • 變更有 onError 處理器
  • 所有使用者操作都有回饋(toast/視覺)

與其他技能的整合

  • graphql-schema:使用帶有適當錯誤處理的變更模式
  • testing-patterns:測試所有 UI 狀態(載入、錯誤、空、成功)
  • formik-patterns:套用表單提交模式

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能