jpskill.com
🛠️ 開発・MCP コミュニティ

rn-async-patterns

Async/await correctness in React Native with Zustand. Use when debugging race conditions, missing awaits, floating promises, or async timing issues in Expo/React Native apps.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o rn-async-patterns.zip https://jpskill.com/download/17855.zip && unzip -o rn-async-patterns.zip && rm rn-async-patterns.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17855.zip -OutFile "$d\rn-async-patterns.zip"; Expand-Archive "$d\rn-async-patterns.zip" -DestinationPath $d -Force; ri "$d\rn-async-patterns.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して rn-async-patterns.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → rn-async-patterns フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

React Native 非同期パターン

問題提起

React Native における非同期処理のバグは、開発環境では動作するものの、負荷がかかった場合や低速なデバイス上で失敗することが多いため、見つけにくいものです。最も一般的な問題は、非同期関数における await の欠落、状態更新間の競合状態、および操作が順番に完了することを前提としていることです。


パターン: Floating Promise の検出

問題: await なしで非同期関数を呼び出すと、バックグラウンドで実行されます。後続のコードがその完了に依存する場合、競合状態が発生します。

例 (retake バグより):

// 修正前 (バグあり) - enableSkillAreaRetake は非同期ですが await されていません
enableSkillAreaRetake(skillArea);         // 実行して放置 ❌
await clearSkillAreaAnswers(skillArea);   // enable が完了する前に実行されます

// 修正後
await enableSkillAreaRetake(skillArea);   // 状態更新を待ちます ✅
await clearSkillAreaAnswers(skillArea);   // 正しい順序で実行されるようになりました

なぜ見つけにくいのか: 両方の関数がシグネチャに async を持っている可能性がありますが、一方だけが await されています。コードは一見「正しく」見えます。

検出:

# Floating Promise の可能性のある箇所を検索 - await のない非同期呼び出し
grep -rn "^\s*[a-zA-Z]*\s*(" --include="*.ts" --include="*.tsx" | \
  grep -v "await\|return\|const\|let\|if\|else\|=>"

防止:

  1. ESLint ルール @typescript-eslint/no-floating-promises - リンター実行時にこれを検出します
  2. コードレビューのトリガー: awaitreturn、または代入なしで、非同期である可能性のある関数を呼び出す行

パターン: 事後条件の検証

問題: 検証せずに非同期呼び出しが成功したと仮定すること。呼び出しが早期に返されたり、サイレントに例外をスローしたり、状態を更新できなかったりする可能性があります。

例 (retake バグより):

// 修正前 (バグあり) - ロードが成功したと仮定
await loadCompletedAssessmentAnswers(id);
// リテイクフローを盲目的に続行...

// 修正後 (防御的)
await loadCompletedAssessmentAnswers(id);
const loaded = useAssessmentStore.getState().completedAssessmentAnswers;
if (Object.keys(loaded).length === 0) {
  throw new Error(
    `Failed to load answers for assessment ${id} - cannot proceed with retake`
  );
}

原則: すべての非同期呼び出しは、そうでないと証明されるまで、失敗する可能性があるものとして扱います。

検証のタイミング:

  • 後続の操作が依存するデータをロードした後
  • 続行する前に完了する必要がある状態更新の後
  • 不可逆的な操作 (送信、削除) の前

パターンテンプレート:

await someAsyncOperation();
const result = getRelevantState();
if (!isValid(result)) {
  throw new Error(`[${functionName}] Post-condition failed: ${diagnosticContext}`);
}

パターン: 非同期関数の識別

問題: すべての非同期関数が非同期に見えるわけではありません。Zustand アクション、コールバック、および Promise を返す関数には、明らかな async キーワードがない場合があります。

隠れた非同期パターン:

// 明らかな非同期
async function fetchData() { ... }

// あまり明らかではない - Promise を返す
function fetchData(): Promise<Data> { ... }

// 隠されている - 実際には非同期である Zustand アクション
const useStore = create((set, get) => ({
  // これは同期に見えますが、内部で非同期を呼び出します
  enableRetake: (area: string) => {
    someAsyncSetup().then(() => {  // ← 隠された非同期!
      set({ retakeAreas: [...get().retakeAreas, area] });
    });
  },
}));

// 適切な非同期 Zustand アクション
const useStore = create((set, get) => ({
  enableRetake: async (area: string) => {
    await someAsyncSetup();
    set({ retakeAreas: [...get().retakeAreas, area] });
  },
}));

検出: 関数のシグネチャと実装を確認します。

# Promise を返す関数を検索
grep -rn "): Promise<" --include="*.ts" --include="*.tsx"

# await が必要な可能性のある .then() チェーンを検索
grep -rn "\.then(" --include="*.ts" --include="*.tsx"

パターン: 逐次的な非同期処理 vs 並列的な非同期処理

問題: 並列処理できる場合に非同期操作を逐次的に実行する (遅い)、または逐次的に実行する必要がある場合に並列的に実行する (競合状態)。

// 逐次的 - 順序が重要な場合は正しい
await enableSkillAreaRetake(skillArea);
await clearSkillAreaAnswers(skillArea);
await loadRetakeQuestions(skillArea);

// 並列的 - 操作が独立している場合は正しい
const [user, settings, history] = await Promise.all([
  fetchUser(id),
  fetchSettings(id),
  fetchHistory(id),
]);

// 間違い - 順序が重要な場合に並列処理
await Promise.all([
  enableSkillAreaRetake(skillArea),   // これらには依存関係があります!
  clearSkillAreaAnswers(skillArea),
]);

意思決定フレームワーク:

操作は状態を共有しますか? 順番に実行する必要がありますか? パターン
いいえ いいえ Promise.all()
はい はい 逐次的な await
はい いいえ 安全のため通常は逐次的

パターン: useEffect での非同期処理

問題: useEffect コールバックは直接非同期にできません。クリーンアップと競合状態に関する一般的な間違い。

// 間違い - useEffect は非同期にできません
useEffect(async () => {
  const data = await fetchData();
  setData(data);
}, []);

// 正しい - 内部の非同期関数
useEffect(() => {
  async function load() {
    const data = await fetchData();
    setData(data);
  }
  load();
}, []);

// より良い - 競合状態のためのクリーンアップ付き
useEffect(() => {
  let cancelled = false;

  async function load() {
    const data = await fetchData();
    if (!cancelled) {
      setData(data);
    }
  }
  load();

  return () => {
    cancelled = true;
  };
}, [dependency]);

ESLint の設定

configs/eslint-async.json の設定を適用して、リンター実行時にこれらの問題を検出します。

{
  "rules": {
    "@typescript-eslint/no-floating-promises": "error",
    "@typescript-eslint/require-await": "warn",
    "@typescript-eslint/await-thenable": "error",
    "@typescript-eslint/no-misused-promises": "error"
  }
}

必須: @typescript-eslint/eslint-plugin と適切な TypeScript 設定。


コードレビューチェックリスト

非同期コードをレビューするときは、以下を確認してください。

  • [ ]

(原文はここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

React Native Async Patterns

Problem Statement

Async bugs in React Native are insidious because they often work in development but fail under load or on slower devices. The most common issues: missing await on async functions, race conditions between state updates, and assuming operations complete in order.


Pattern: Floating Promise Detection

Problem: Calling an async function without await causes it to run in the background. If subsequent code depends on its completion, you get a race condition.

Example (from retake bug):

// Before (buggy) - enableSkillAreaRetake is async but not awaited
enableSkillAreaRetake(skillArea);         // Fire and forget ❌
await clearSkillAreaAnswers(skillArea);   // Runs before enable completes

// After (fixed)
await enableSkillAreaRetake(skillArea);   // Wait for state update ✅
await clearSkillAreaAnswers(skillArea);   // Now runs in correct order

Why it's subtle: Both functions might have async in their signature, but only one was awaited. The code "looks right" at a glance.

Detection:

# Find potential floating promises - async calls without await
grep -rn "^\s*[a-zA-Z]*\s*(" --include="*.ts" --include="*.tsx" | \
  grep -v "await\|return\|const\|let\|if\|else\|=>"

Prevention:

  1. ESLint rule @typescript-eslint/no-floating-promises - catches this at lint time
  2. Code review trigger: Any line calling a function that might be async without await, return, or assignment

Pattern: Post-Condition Validation

Problem: Assuming an async call succeeded without verifying. The call might return early, throw silently, or fail to update state.

Example (from retake bug):

// Before (buggy) - assumed load worked
await loadCompletedAssessmentAnswers(id);
// Proceeded blindly with retake flow...

// After (defensive)
await loadCompletedAssessmentAnswers(id);
const loaded = useAssessmentStore.getState().completedAssessmentAnswers;
if (Object.keys(loaded).length === 0) {
  throw new Error(
    `Failed to load answers for assessment ${id} - cannot proceed with retake`
  );
}

Principle: Treat every async call as potentially failed until proven otherwise.

When to validate:

  • After loading data that subsequent operations depend on
  • After state updates that must complete before continuing
  • Before irreversible operations (submissions, deletions)

Pattern template:

await someAsyncOperation();
const result = getRelevantState();
if (!isValid(result)) {
  throw new Error(`[${functionName}] Post-condition failed: ${diagnosticContext}`);
}

Pattern: Async Function Identification

Problem: Not all async functions look async. Zustand actions, callbacks, and promise-returning functions may not have obvious async keywords.

Hidden async patterns:

// Obvious async
async function fetchData() { ... }

// Less obvious - returns Promise
function fetchData(): Promise<Data> { ... }

// Hidden - Zustand action that's actually async
const useStore = create((set, get) => ({
  // This looks sync but calls async internally
  enableRetake: (area: string) => {
    someAsyncSetup().then(() => {  // ← Hidden async!
      set({ retakeAreas: [...get().retakeAreas, area] });
    });
  },
}));

// Proper async Zustand action
const useStore = create((set, get) => ({
  enableRetake: async (area: string) => {
    await someAsyncSetup();
    set({ retakeAreas: [...get().retakeAreas, area] });
  },
}));

Detection: Check function signatures and implementations:

# Find functions returning Promise
grep -rn "): Promise<" --include="*.ts" --include="*.tsx"

# Find .then() chains that might need await
grep -rn "\.then(" --include="*.ts" --include="*.tsx"

Pattern: Sequential vs Parallel Async

Problem: Running async operations sequentially when they could be parallel (slow), or parallel when they must be sequential (race condition).

// Sequential - correct when order matters
await enableSkillAreaRetake(skillArea);
await clearSkillAreaAnswers(skillArea);
await loadRetakeQuestions(skillArea);

// Parallel - correct when operations are independent
const [user, settings, history] = await Promise.all([
  fetchUser(id),
  fetchSettings(id),
  fetchHistory(id),
]);

// WRONG - parallel when order matters
await Promise.all([
  enableSkillAreaRetake(skillArea),   // These have dependencies!
  clearSkillAreaAnswers(skillArea),
]);

Decision framework:

Operations share state? Must run in order? Pattern
No No Promise.all()
Yes Yes Sequential await
Yes No Usually sequential to be safe

Pattern: Async in useEffect

Problem: useEffect callbacks can't be async directly. Common mistakes with cleanup and race conditions.

// WRONG - useEffect can't be async
useEffect(async () => {
  const data = await fetchData();
  setData(data);
}, []);

// CORRECT - async function inside
useEffect(() => {
  async function load() {
    const data = await fetchData();
    setData(data);
  }
  load();
}, []);

// BETTER - with cleanup for race conditions
useEffect(() => {
  let cancelled = false;

  async function load() {
    const data = await fetchData();
    if (!cancelled) {
      setData(data);
    }
  }
  load();

  return () => {
    cancelled = true;
  };
}, [dependency]);

ESLint Configuration

Apply config from configs/eslint-async.json to catch these issues at lint time:

{
  "rules": {
    "@typescript-eslint/no-floating-promises": "error",
    "@typescript-eslint/require-await": "warn",
    "@typescript-eslint/await-thenable": "error",
    "@typescript-eslint/no-misused-promises": "error"
  }
}

Required: @typescript-eslint/eslint-plugin and proper TypeScript configuration.


Code Review Checklist

When reviewing async code, check:

  • [ ] Every async function call is either awaited, returned, or explicitly fire-and-forget with comment
  • [ ] Operations that depend on each other are sequenced with await
  • [ ] Post-conditions validated after critical async operations
  • [ ] useEffect with async uses the inner function pattern
  • [ ] Race conditions considered when component could unmount during async
  • [ ] Error handling exists for async failures

Quick Debugging

When async timing issues occur:

// Add timestamps to trace execution order
console.log(`[${Date.now()}] Starting enableRetake`);
await enableSkillAreaRetake(skillArea);
console.log(`[${Date.now()}] Finished enableRetake`);
console.log(`[${Date.now()}] Starting clearAnswers`);
await clearSkillAreaAnswers(skillArea);
console.log(`[${Date.now()}] Finished clearAnswers`);

Look for:

  • Operations finishing out of expected order
  • Operations starting before previous ones complete
  • Suspiciously fast "completions" (might not have awaited)