Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/async-defer-await.md
1---2title: Defer Await Until Needed3impact: HIGH4impactDescription: avoids blocking unused code paths5tags: async, await, conditional, optimization6---78## Defer Await Until Needed910Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.1112**Incorrect (blocks both branches):**1314```typescript15async function handleRequest(userId: string, skipProcessing: boolean) {16const userData = await fetchUserData(userId)1718if (skipProcessing) {19// Returns immediately but still waited for userData20return { skipped: true }21}2223// Only this branch uses userData24return processUserData(userData)25}26```2728**Correct (only blocks when needed):**2930```typescript31async function handleRequest(userId: string, skipProcessing: boolean) {32if (skipProcessing) {33// Returns immediately without waiting34return { skipped: true }35}3637// Fetch only when needed38const userData = await fetchUserData(userId)39return processUserData(userData)40}41```4243**Another example (early return optimization):**4445```typescript46// Incorrect: always fetches permissions47async function updateResource(resourceId: string, userId: string) {48const permissions = await fetchPermissions(userId)49const resource = await getResource(resourceId)5051if (!resource) {52return { error: 'Not found' }53}5455if (!permissions.canEdit) {56return { error: 'Forbidden' }57}5859return await updateResourceData(resource, permissions)60}6162// Correct: fetches only when needed63async function updateResource(resourceId: string, userId: string) {64const resource = await getResource(resourceId)6566if (!resource) {67return { error: 'Not found' }68}6970const permissions = await fetchPermissions(userId)7172if (!permissions.canEdit) {73return { error: 'Forbidden' }74}7576return await updateResourceData(resource, permissions)77}78```7980This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.8182For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).83