react-async-patterns
Async/await correctness in React with Zustand. Use when debugging race conditions, missing awaits, floating promises, or async timing issues. Works for both React web and React Native.
Best use case
react-async-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Async/await correctness in React with Zustand. Use when debugging race conditions, missing awaits, floating promises, or async timing issues. Works for both React web and React Native.
Teams using react-async-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/react-async-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How react-async-patterns Compares
| Feature / Agent | react-async-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Async/await correctness in React with Zustand. Use when debugging race conditions, missing awaits, floating promises, or async timing issues. Works for both React web and React Native.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# React Async Patterns
## Problem Statement
Async bugs in React are insidious because they often work in development but fail under load or in edge cases. 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.
```typescript
// Before (buggy) - saveData is async but not awaited
saveData(item); // Fire and forget ❌
await processData(item); // Runs before save completes
// After (fixed)
await saveData(item); // Wait for state update ✅
await processData(item); // 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:**
```bash
# 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.
```typescript
// Before (buggy) - assumed load worked
await loadData(id);
// Proceeded blindly with next steps...
// After (defensive)
await loadData(id);
const loaded = useStore.getState().data;
if (Object.keys(loaded).length === 0) {
throw new Error(
`Failed to load data for ${id} - cannot proceed`
);
}
```
**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:**
```typescript
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:**
```typescript
// 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
enableFeature: (id: string) => {
someAsyncSetup().then(() => { // ← Hidden async!
set({ features: [...get().features, id] });
});
},
}));
// Proper async Zustand action
const useStore = create((set, get) => ({
enableFeature: async (id: string) => {
await someAsyncSetup();
set({ features: [...get().features, id] });
},
}));
```
**Detection:** Check function signatures and implementations:
```bash
# 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).
```typescript
// Sequential - correct when order matters
await stepOne();
await stepTwo();
await stepThree();
// 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([
stepOne(), // These have dependencies!
stepTwo(),
]);
```
**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.
```typescript
// 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]);
// BEST - use AbortController for fetch
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(url, { signal: controller.signal });
const data = await response.json();
setData(data);
} catch (error) {
if (error.name !== 'AbortError') {
setError(error);
}
}
}
load();
return () => controller.abort();
}, [url]);
```
---
## Pattern: React Query / TanStack Query
**Problem:** Manual async state management is error-prone. Use a library.
```typescript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
// Fetching data
function UserProfile({ userId }) {
const { data, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
});
if (isLoading) return <Spinner />;
if (error) return <Error error={error} />;
return <Profile user={data} />;
}
// Mutations with cache invalidation
function UpdateUser() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: updateUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['user'] });
},
});
return (
<button onClick={() => mutation.mutate(userData)}>
Save
</button>
);
}
```
---
## ESLint Configuration
Add these rules to catch async issues at lint time:
```json
{
"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 `await`ed, `return`ed, 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
- [ ] AbortController used for fetch calls that should be cancellable
---
## Quick Debugging
When async timing issues occur:
```typescript
// Add timestamps to trace execution order
console.log(`[${Date.now()}] Starting step 1`);
await stepOne();
console.log(`[${Date.now()}] Finished step 1`);
console.log(`[${Date.now()}] Starting step 2`);
await stepTwo();
console.log(`[${Date.now()}] Finished step 2`);
```
Look for:
- Operations finishing out of expected order
- Operations starting before previous ones complete
- Suspiciously fast "completions" (might not have awaited)Related Skills
exa-sdk-patterns
Apply production-ready exa-js SDK patterns with type safety, singletons, and wrappers. Use when implementing Exa integrations, refactoring SDK usage, or establishing team coding standards for Exa. Trigger with phrases like "exa SDK patterns", "exa best practices", "exa code patterns", "idiomatic exa", "exa wrapper".
exa-reliability-patterns
Implement Exa reliability patterns: query fallback chains, circuit breakers, and graceful degradation. Use when building fault-tolerant Exa integrations, implementing fallback strategies, or adding resilience to production search services. Trigger with phrases like "exa reliability", "exa circuit breaker", "exa fallback", "exa resilience", "exa graceful degradation".
evernote-sdk-patterns
Advanced Evernote SDK patterns and best practices. Use when implementing complex note operations, batch processing, search queries, or optimizing SDK usage. Trigger with phrases like "evernote sdk patterns", "evernote best practices", "evernote advanced", "evernote batch operations".
elevenlabs-sdk-patterns
Apply production-ready ElevenLabs SDK patterns for TypeScript and Python. Use when implementing ElevenLabs integrations, refactoring SDK usage, or establishing team coding standards for audio AI applications. Trigger: "elevenlabs SDK patterns", "elevenlabs best practices", "elevenlabs code patterns", "idiomatic elevenlabs", "elevenlabs typescript".
documenso-sdk-patterns
Apply production-ready Documenso SDK patterns for TypeScript and Python. Use when implementing Documenso integrations, refactoring SDK usage, or establishing team coding standards for Documenso. Trigger with phrases like "documenso SDK patterns", "documenso best practices", "documenso code patterns", "idiomatic documenso".
deepgram-sdk-patterns
Apply production-ready Deepgram SDK patterns for TypeScript and Python. Use when implementing Deepgram integrations, refactoring SDK usage, or establishing team coding standards for Deepgram. Trigger: "deepgram SDK patterns", "deepgram best practices", "deepgram code patterns", "idiomatic deepgram", "deepgram typescript".
databricks-sdk-patterns
Apply production-ready Databricks SDK patterns for Python and REST API. Use when implementing Databricks integrations, refactoring SDK usage, or establishing team coding standards for Databricks. Trigger with phrases like "databricks SDK patterns", "databricks best practices", "databricks code patterns", "idiomatic databricks".
customerio-sdk-patterns
Apply production-ready Customer.io SDK patterns. Use when implementing typed clients, retry logic, event batching, or singleton management for customerio-node. Trigger: "customer.io best practices", "customer.io patterns", "production customer.io", "customer.io architecture", "customer.io singleton".
customerio-reliability-patterns
Implement Customer.io reliability and fault-tolerance patterns. Use when building circuit breakers, fallback queues, idempotency, or graceful degradation for Customer.io integrations. Trigger: "customer.io reliability", "customer.io resilience", "customer.io circuit breaker", "customer.io fault tolerance".
coreweave-sdk-patterns
Production-ready patterns for CoreWeave GPU workload management with kubectl and Python. Use when building inference clients, managing GPU deployments programmatically, or creating reusable CoreWeave deployment templates. Trigger with phrases like "coreweave patterns", "coreweave client", "coreweave Python", "coreweave deployment template".
cohere-sdk-patterns
Apply production-ready Cohere SDK patterns for TypeScript and Python. Use when implementing Cohere integrations, refactoring SDK usage, or establishing team coding standards for Cohere API v2. Trigger with phrases like "cohere SDK patterns", "cohere best practices", "cohere code patterns", "idiomatic cohere", "cohere wrapper".
coderabbit-sdk-patterns
Apply production-ready CodeRabbit automation patterns using GitHub API and PR comments. Use when building automation around CodeRabbit reviews, processing review feedback programmatically, or integrating CodeRabbit into custom workflows. Trigger with phrases like "coderabbit automation", "coderabbit API patterns", "automate coderabbit", "coderabbit github api", "process coderabbit reviews".