Communitygithub.com

ComeOnOliver/skillshub

最新のReact UIパターン集:ローディング状態、エラーハンドリング、データフェッチを効率的に扱います。UIコンポーネント構築、非同期データ処理、UI状態管理に最適です。

skillshub とは?

このスキルは、ReactアプリケーションにおけるUI状態管理のベストプラクティスを提供します。ローディング状態は「データがないときにのみ表示する」という黄金律に基づき、スピナーやスケルトンを適切に使い分けます。エラーハンドリングでは、エラーを絶対に無視せず、インライン、トースト、バナー、フルスクリーンという階層的な表示を推奨します。ボタンは非同期操作中に常に無効化し、ローディングインジケータを表示します。また、空の状態(Empty State)をすべてのリストに必須とし、楽観的更新やプログレッシブディスクロージャといった原則もカバーしています。Apollo ClientやGraphQLなどのデータフェッチライブラリと組み合わせて使用することを想定しており、具体的なコード例(TypeScript)とアンチパターンが豊富に含まれています。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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 />; // 再フェッチでちらつく!

ローディング状態の決定木

エラーはあるか?
  → はい: 再試行オプション付きのエラー状態を表示
  → いいえ: 次へ

ローディング中かつデータがないか?
  → はい: ローディングインジケータ(スピナー/スケルトン)を表示
  → いいえ: 次へ

データはあるか?
  → はい、アイテムあり: データを表示
  → はい、ただし空: 空の状態を表示
  → いいえ: ローディングを表示(フォールバック)

スケルトン vs スピナー

スケルトンを使用する場合スピナーを使用する場合
既知のコンテンツ形状未知のコンテンツ形状
リスト/カードレイアウトモーダルアクション
初期ページ読み込みボタン送信
コンテンツプレースホルダーインライン操作

エラーハンドリングパターン

エラーハンドリングの階層

1. インラインエラー(フィールドレベル)→ フォームバリデーションエラー
2. トースト通知 → 回復可能なエラー、ユーザーが再試行可能
3. エラーバナー → ページレベルエラー、データは部分的に使用可能
4. フルエラー画面 → 回復不可能、ユーザーの操作が必要

エラーは常に表示する

重要: エラーを黙って無視しないこと。

// 正しい - エラーは常にユーザーに表示される
const [createItem, { loading }] = useCreateItemMutation({
  onCompleted: () => {
    toast.success({ title: 'アイテムを作成しました' });
  },
  onError: (error) => {
    console.error('createItem failed:', 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('operation failed:', error);
  toast.error({ title: '操作に失敗しました' });
}

ボタンの状態

// 間違い - 送信中でもボタンが無効化されない
<Button onClick={submit}>送信</Button>

// 正しい - 無効化され、ローディングを表示
<Button onClick={submit} disabled={loading} isLoading={loading}>
  送信
</Button>

チェックリスト

UIコンポーネントを完了する前に:

UI状態:

  • エラー状態が処理され、ユーザーに表示されている
  • ローディング状態はデータがない場合のみ表示される
  • コレクションに対して空の状態が提供されている
  • 非同期操作中はボタンが無効化されている
  • ボタンは適切な場合にローディングインジケータを表示する

データとミューテーション:

  • ミューテーションにonErrorハンドラがある
  • すべてのユーザーアクションにフィードバック(トースト/視覚)がある

他のスキルとの連携

  • 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

関連スキル