[
{
"ruleId": "",
"ruleTitle": "Do Not Put Effect Events in Dependency Arrays",
"type": "bad",
"code": "import { useEffect, useEffectEvent } from 'react'\n\nfunction ChatRoom({ roomId, onConnected }: {\n roomId: string\n onConnected: () => void\n}) {\n const handleConnected = useEffectEvent(onConnected)\n\n useEffect(() => {\n const connection = createConnection(roomId)\n connection.on('connected', handleConnected)\n connection.connect()\n\n return () => connection.disconnect()\n }, [roomId, handleConnected])\n}",
"language": "tsx",
"description": "Effect Event added as a dependency"
},
{
"ruleId": "",
"ruleTitle": "Do Not Put Effect Events in Dependency Arrays",
"type": "good",
"code": "import { useEffect, useEffectEvent } from 'react'\n\nfunction ChatRoom({ roomId, onConnected }: {\n roomId: string\n onConnected: () => void\n}) {\n const handleConnected = useEffectEvent(onConnected)\n\n useEffect(() => {\n const connection = createConnection(roomId)\n connection.on('connected', handleConnected)\n connection.connect()\n\n return () => connection.disconnect()\n }, [roomId])\n}",
"language": "tsx",
"description": "depend on reactive values, not the Effect Event"
},
{
"ruleId": "",
"ruleTitle": "Store Event Handlers in Refs",
"type": "bad",
"code": "function useWindowEvent(event: string, handler: (e) => void) {\n useEffect(() => {\n window.addEventListener(event, handler)\n return () => window.removeEventListener(event, handler)\n }, [event, handler])\n}",
"language": "tsx",
"description": "re-subscribes on every render"
},
{
"ruleId": "",
"ruleTitle": "Store Event Handlers in Refs",
"type": "good",
"code": "import { useEffectEvent } from 'react'\n\nfunction useWindowEvent(event: string, handler: (e) => void) {\n const onEvent = useEffectEvent(handler)\n\n useEffect(() => {\n window.addEventListener(event, onEvent)\n return () => window.removeEventListener(event, onEvent)\n }, [event])\n}",
"language": "tsx",
"description": "stable subscription"
},
{
"ruleId": "",
"ruleTitle": "Initialize App Once, Not Per Mount",
"type": "bad",
"code": "function Comp() {\n useEffect(() => {\n loadFromStorage()\n checkAuthToken()\n }, [])\n\n // ...\n}",
"language": "tsx",
"description": "runs twice in dev, re-runs on remount"
},
{
"ruleId": "",
"ruleTitle": "Initialize App Once, Not Per Mount",
"type": "good",
"code": "let didInit = false\n\nfunction Comp() {\n useEffect(() => {\n if (didInit) return\n didInit = true\n loadFromStorage()\n checkAuthToken()\n }, [])\n\n // ...\n}",
"language": "tsx",
"description": "once per app load"
},
{
"ruleId": "",
"ruleTitle": "useEffectEvent for Stable Callback Refs",
"type": "bad",
"code": "function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {\n const [query, setQuery] = useState('')\n\n useEffect(() => {\n const timeout = setTimeout(() => onSearch(query), 300)\n return () => clearTimeout(timeout)\n }, [query, onSearch])\n}",
"language": "tsx",
"description": "effect re-runs on every callback change"
},
{
"ruleId": "",
"ruleTitle": "useEffectEvent for Stable Callback Refs",
"type": "good",
"code": "import { useEffectEvent } from 'react';\n\nfunction SearchInput({ onSearch }: { onSearch: (q: string) => void }) {\n const [query, setQuery] = useState('')\n const onSearchEvent = useEffectEvent(onSearch)\n\n useEffect(() => {\n const timeout = setTimeout(() => onSearchEvent(query), 300)\n return () => clearTimeout(timeout)\n }, [query])\n}",
"language": "tsx",
"description": "using React's useEffectEvent"
},
{
"ruleId": "",
"ruleTitle": "Prevent Waterfall Chains in API Routes",
"type": "bad",
"code": "export async function GET(request: Request) {\n const session = await auth()\n const config = await fetchConfig()\n const data = await fetchData(session.user.id)\n return Response.json({ data, config })\n}",
"language": "typescript",
"description": "config waits for auth, data waits for both"
},
{
"ruleId": "",
"ruleTitle": "Prevent Waterfall Chains in API Routes",
"type": "good",
"code": "export async function GET(request: Request) {\n const sessionPromise = auth()\n const configPromise = fetchConfig()\n const session = await sessionPromise\n const [config, data] = await Promise.all([\n configPromise,\n fetchData(session.user.id)\n ])\n return Response.json({ data, config })\n}",
"language": "typescript",
"description": "auth and config start immediately"
},
{
"ruleId": "",
"ruleTitle": "Check Cheap Conditions Before Async Flags",
"type": "bad",
"code": "const someFlag = await getFlag()\n\nif (someFlag && someCondition) {\n // ...\n}",
"language": "typescript",
"description": "Incorrect example for Check Cheap Conditions Before Async Flags"
},
{
"ruleId": "",
"ruleTitle": "Check Cheap Conditions Before Async Flags",
"type": "good",
"code": "if (someCondition) {\n const someFlag = await getFlag()\n if (someFlag) {\n // ...\n }\n}",
"language": "typescript",
"description": "Correct example for Check Cheap Conditions Before Async Flags"
},
{
"ruleId": "",
"ruleTitle": "Defer Await Until Needed",
"type": "bad",
"code": "async function handleRequest(userId: string, skipProcessing: boolean) {\n const userData = await fetchUserData(userId)\n \n if (skipProcessing) {\n // Returns immediately but still waited for userData\n return { skipped: true }\n }\n \n // Only this branch uses userData\n return processUserData(userData)\n}",
"language": "typescript",
"description": "blocks both branches"
},
{
"ruleId": "",
"ruleTitle": "Defer Await Until Needed",
"type": "good",
"code": "async function handleRequest(userId: string, skipProcessing: boolean) {\n if (skipProcessing) {\n // Returns immediately without waiting\n return { skipped: true }\n }\n \n // Fetch only when needed\n const userData = await fetchUserData(userId)\n return processUserData(userData)\n}",
"language": "typescript",
"description": "only blocks when needed"
},
{
"ruleId": "",
"ruleTitle": "Dependency-Based Parallelization",
"type": "bad",
"code": "const [user, config] = await Promise.all([\n fetchUser(),\n fetchConfig()\n])\nconst profile = await fetchProfile(user.id)",
"language": "typescript",
"description": "profile waits for config unnecessarily"
},
{
"ruleId": "",
"ruleTitle": "Dependency-Based Parallelization",
"type": "good",
"code": "import { all } from 'better-all'\n\nconst { user, config, profile } = await all({\n async user() { return fetchUser() },\n async config() { return fetchConfig() },\n async profile() {\n return fetchProfile((await this.$.user).id)\n }\n})",
"language": "typescript",
"description": "config and profile run in parallel"
},
{
"ruleId": "",
"ruleTitle": "Promise.all() for Independent Operations",
"type": "bad",
"code": "const user = await fetchUser()\nconst posts = await fetchPosts()\nconst comments = await fetchComments()",
"language": "typescript",
"description": "sequential execution, 3 round trips"
},
{
"ruleId": "",
"ruleTitle": "Promise.all() for Independent Operations",
"type": "good",
"code": "const [user, posts, comments] = await Promise.all([\n fetchUser(),\n fetchPosts(),\n fetchComments()\n])",
"language": "typescript",
"description": "parallel execution, 1 round trip"
},
{
"ruleId": "",
"ruleTitle": "Strategic Suspense Boundaries",
"type": "bad",
"code": "async function Page() {\n const data = await fetchData() // Blocks entire page\n \n return (\n
\n
Sidebar
\n
Header
\n
\n \n
\n
Footer
\n
\n )\n}",
"language": "tsx",
"description": "wrapper blocked by data fetching"
},
{
"ruleId": "",
"ruleTitle": "Strategic Suspense Boundaries",
"type": "good",
"code": "function Page() {\n return (\n \n
Sidebar
\n
Header
\n
\n }>\n \n \n
\n
Footer
\n
\n )\n}\n\nasync function DataDisplay() {\n const data = await fetchData() // Only blocks this component\n return {data.content}
\n}",
"language": "tsx",
"description": "wrapper shows immediately, data streams in"
},
{
"ruleId": "",
"ruleTitle": "Prefer Statically Analyzable Paths",
"type": "bad",
"code": "const PAGE_MODULES = {\n home: './pages/home',\n settings: './pages/settings',\n} as const\n\nconst Page = await import(PAGE_MODULES[pageName])",
"language": "ts",
"description": "the bundler cannot tell what may be imported"
},
{
"ruleId": "",
"ruleTitle": "Prefer Statically Analyzable Paths",
"type": "good",
"code": "const PAGE_MODULES = {\n home: () => import('./pages/home'),\n settings: () => import('./pages/settings'),\n} as const\n\nconst Page = await PAGE_MODULES[pageName]()",
"language": "ts",
"description": "use an explicit map of allowed modules"
},
{
"ruleId": "",
"ruleTitle": "Prefer Statically Analyzable Paths",
"type": "bad",
"code": "const baseDir = path.join(process.cwd(), 'content/' + contentKind)",
"language": "ts",
"description": "a 2-value enum still hides the final path from static analysis"
},
{
"ruleId": "",
"ruleTitle": "Prefer Statically Analyzable Paths",
"type": "good",
"code": "const baseDir =\n kind === ContentKind.Blog\n ? path.join(process.cwd(), 'content/blog')\n : path.join(process.cwd(), 'content/docs')",
"language": "ts",
"description": "make each final path literal at the callsite"
},
{
"ruleId": "",
"ruleTitle": "Avoid Barrel File Imports",
"type": "bad",
"code": "import { Check, X, Menu } from 'lucide-react'\n// Loads 1,583 modules, takes ~2.8s extra in dev\n// Runtime cost: 200-800ms on every cold start\n\nimport { Button, TextField } from '@mui/material'\n// Loads 2,225 modules, takes ~4.2s extra in dev",
"language": "tsx",
"description": "imports entire library"
},
{
"ruleId": "",
"ruleTitle": "Avoid Barrel File Imports",
"type": "good",
"code": "// Keep the standard imports - Next.js transforms them to direct imports\nimport { Check, X, Menu } from 'lucide-react'\n// Full TypeScript support, no manual path wrangling",
"language": "tsx",
"description": "Correct - Next.js 13.5+ (recommended) example for Avoid Barrel File Imports"
},
{
"ruleId": "",
"ruleTitle": "Avoid Barrel File Imports",
"type": "good",
"code": "import Button from '@mui/material/Button'\nimport TextField from '@mui/material/TextField'\n// Loads only what you use",
"language": "tsx",
"description": "Correct - Direct imports (non-Next.js projects) example for Avoid Barrel File Imports"
},
{
"ruleId": "",
"ruleTitle": "Defer Non-Critical Third-Party Libraries",
"type": "bad",
"code": "import { Analytics } from '@vercel/analytics/react'\n\nexport default function RootLayout({ children }) {\n return (\n \n \n {children}\n \n \n \n )\n}",
"language": "tsx",
"description": "blocks initial bundle"
},
{
"ruleId": "",
"ruleTitle": "Defer Non-Critical Third-Party Libraries",
"type": "good",
"code": "import dynamic from 'next/dynamic'\n\nconst Analytics = dynamic(\n () => import('@vercel/analytics/react').then(m => m.Analytics),\n { ssr: false }\n)\n\nexport default function RootLayout({ children }) {\n return (\n \n \n {children}\n \n \n \n )\n}",
"language": "tsx",
"description": "loads after hydration"
},
{
"ruleId": "",
"ruleTitle": "Dynamic Imports for Heavy Components",
"type": "bad",
"code": "import { MonacoEditor } from './monaco-editor'\n\nfunction CodePanel({ code }: { code: string }) {\n return \n}",
"language": "tsx",
"description": "Monaco bundles with main chunk ~300KB"
},
{
"ruleId": "",
"ruleTitle": "Dynamic Imports for Heavy Components",
"type": "good",
"code": "import dynamic from 'next/dynamic'\n\nconst MonacoEditor = dynamic(\n () => import('./monaco-editor').then(m => m.MonacoEditor),\n { ssr: false }\n)\n\nfunction CodePanel({ code }: { code: string }) {\n return \n}",
"language": "tsx",
"description": "Monaco loads on demand"
},
{
"ruleId": "",
"ruleTitle": "Deduplicate Global Event Listeners",
"type": "bad",
"code": "function useKeyboardShortcut(key: string, callback: () => void) {\n useEffect(() => {\n const handler = (e: KeyboardEvent) => {\n if (e.metaKey && e.key === key) {\n callback()\n }\n }\n window.addEventListener('keydown', handler)\n return () => window.removeEventListener('keydown', handler)\n }, [key, callback])\n}",
"language": "tsx",
"description": "N instances = N listeners"
},
{
"ruleId": "",
"ruleTitle": "Deduplicate Global Event Listeners",
"type": "good",
"code": "import useSWRSubscription from 'swr/subscription'\n\n// Module-level Map to track callbacks per key\nconst keyCallbacks = new Map void>>()\n\nfunction useKeyboardShortcut(key: string, callback: () => void) {\n // Register this callback in the Map\n useEffect(() => {\n if (!keyCallbacks.has(key)) {\n keyCallbacks.set(key, new Set())\n }\n keyCallbacks.get(key)!.add(callback)\n\n return () => {\n const set = keyCallbacks.get(key)\n if (set) {\n set.delete(callback)\n if (set.size === 0) {\n keyCallbacks.delete(key)\n }\n }\n }\n }, [key, callback])\n\n useSWRSubscription('global-keydown', () => {\n const handler = (e: KeyboardEvent) => {\n if (e.metaKey && keyCallbacks.has(e.key)) {\n keyCallbacks.get(e.key)!.forEach(cb => cb())\n }\n }\n window.addEventListener('keydown', handler)\n return () => window.removeEventListener('keydown', handler)\n })\n}\n\nfunction Profile() {\n // Multiple shortcuts will share the same listener\n useKeyboardShortcut('p', () => { /* ... */ }) \n useKeyboardShortcut('k', () => { /* ... */ })\n // ...\n}",
"language": "tsx",
"description": "N instances = 1 listener"
},
{
"ruleId": "",
"ruleTitle": "Version and Minimize localStorage Data",
"type": "bad",
"code": "// No version, stores everything, no error handling\nlocalStorage.setItem('userConfig', JSON.stringify(fullUserObject))\nconst data = localStorage.getItem('userConfig')",
"language": "typescript",
"description": "Incorrect example for Version and Minimize localStorage Data"
},
{
"ruleId": "",
"ruleTitle": "Version and Minimize localStorage Data",
"type": "good",
"code": "const VERSION = 'v2'\n\nfunction saveConfig(config: { theme: string; language: string }) {\n try {\n localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))\n } catch {\n // Throws in incognito/private browsing, quota exceeded, or disabled\n }\n}\n\nfunction loadConfig() {\n try {\n const data = localStorage.getItem(`userConfig:${VERSION}`)\n return data ? JSON.parse(data) : null\n } catch {\n return null\n }\n}\n\n// Migration from v1 to v2\nfunction migrate() {\n try {\n const v1 = localStorage.getItem('userConfig:v1')\n if (v1) {\n const old = JSON.parse(v1)\n saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })\n localStorage.removeItem('userConfig:v1')\n }\n } catch {}\n}",
"language": "typescript",
"description": "Correct example for Version and Minimize localStorage Data"
},
{
"ruleId": "",
"ruleTitle": "Use Passive Event Listeners for Scrolling Performance",
"type": "bad",
"code": "useEffect(() => {\n const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)\n const handleWheel = (e: WheelEvent) => console.log(e.deltaY)\n \n document.addEventListener('touchstart', handleTouch)\n document.addEventListener('wheel', handleWheel)\n \n return () => {\n document.removeEventListener('touchstart', handleTouch)\n document.removeEventListener('wheel', handleWheel)\n }\n}, [])",
"language": "typescript",
"description": "Incorrect example for Use Passive Event Listeners for Scrolling Performance"
},
{
"ruleId": "",
"ruleTitle": "Use Passive Event Listeners for Scrolling Performance",
"type": "good",
"code": "useEffect(() => {\n const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)\n const handleWheel = (e: WheelEvent) => console.log(e.deltaY)\n \n document.addEventListener('touchstart', handleTouch, { passive: true })\n document.addEventListener('wheel', handleWheel, { passive: true })\n \n return () => {\n document.removeEventListener('touchstart', handleTouch)\n document.removeEventListener('wheel', handleWheel)\n }\n}, [])",
"language": "typescript",
"description": "Correct example for Use Passive Event Listeners for Scrolling Performance"
},
{
"ruleId": "",
"ruleTitle": "Use SWR for Automatic Deduplication",
"type": "bad",
"code": "function UserList() {\n const [users, setUsers] = useState([])\n useEffect(() => {\n fetch('/api/users')\n .then(r => r.json())\n .then(setUsers)\n }, [])\n}",
"language": "tsx",
"description": "no deduplication, each instance fetches"
},
{
"ruleId": "",
"ruleTitle": "Use SWR for Automatic Deduplication",
"type": "good",
"code": "import useSWR from 'swr'\n\nfunction UserList() {\n const { data: users } = useSWR('/api/users', fetcher)\n}",
"language": "tsx",
"description": "multiple instances share one request"
},
{
"ruleId": "",
"ruleTitle": "Avoid Layout Thrashing",
"type": "bad",
"code": "function layoutThrashing(element: HTMLElement) {\n element.style.width = '100px'\n const width = element.offsetWidth // Forces reflow\n element.style.height = '200px'\n const height = element.offsetHeight // Forces another reflow\n}",
"language": "typescript",
"description": "interleaved reads and writes force reflows"
},
{
"ruleId": "",
"ruleTitle": "Avoid Layout Thrashing",
"type": "good",
"code": "function updateElementStyles(element: HTMLElement) {\n // Batch all writes together\n element.style.width = '100px'\n element.style.height = '200px'\n element.style.backgroundColor = 'blue'\n element.style.border = '1px solid black'\n \n // Read after all writes are done (single reflow)\n const { width, height } = element.getBoundingClientRect()\n}",
"language": "typescript",
"description": "batch writes, then read once"
},
{
"ruleId": "",
"ruleTitle": "Avoid Layout Thrashing",
"type": "good",
"code": "function updateElementStyles(element: HTMLElement) {\n element.classList.add('highlighted-box')\n \n const { width, height } = element.getBoundingClientRect()\n}",
"language": "typescript",
"description": "batch reads, then writes"
},
{
"ruleId": "",
"ruleTitle": "Cache Repeated Function Calls",
"type": "bad",
"code": "function ProjectList({ projects }: { projects: Project[] }) {\n return (\n \n {projects.map(project => {\n // slugify() called 100+ times for same project names\n const slug = slugify(project.name)\n \n return
\n })}\n
\n )\n}",
"language": "typescript",
"description": "redundant computation"
},
{
"ruleId": "",
"ruleTitle": "Cache Repeated Function Calls",
"type": "good",
"code": "// Module-level cache\nconst slugifyCache = new Map()\n\nfunction cachedSlugify(text: string): string {\n if (slugifyCache.has(text)) {\n return slugifyCache.get(text)!\n }\n const result = slugify(text)\n slugifyCache.set(text, result)\n return result\n}\n\nfunction ProjectList({ projects }: { projects: Project[] }) {\n return (\n \n {projects.map(project => {\n // Computed only once per unique project name\n const slug = cachedSlugify(project.name)\n \n return
\n })}\n
\n )\n}",
"language": "typescript",
"description": "cached results"
},
{
"ruleId": "",
"ruleTitle": "Cache Property Access in Loops",
"type": "bad",
"code": "for (let i = 0; i < arr.length; i++) {\n process(obj.config.settings.value)\n}",
"language": "typescript",
"description": "3 lookups × N iterations"
},
{
"ruleId": "",
"ruleTitle": "Cache Property Access in Loops",
"type": "good",
"code": "const value = obj.config.settings.value\nconst len = arr.length\nfor (let i = 0; i < len; i++) {\n process(value)\n}",
"language": "typescript",
"description": "1 lookup total"
},
{
"ruleId": "",
"ruleTitle": "Cache Storage API Calls",
"type": "bad",
"code": "function getTheme() {\n return localStorage.getItem('theme') ?? 'light'\n}\n// Called 10 times = 10 storage reads",
"language": "typescript",
"description": "reads storage on every call"
},
{
"ruleId": "",
"ruleTitle": "Cache Storage API Calls",
"type": "good",
"code": "const storageCache = new Map()\n\nfunction getLocalStorage(key: string) {\n if (!storageCache.has(key)) {\n storageCache.set(key, localStorage.getItem(key))\n }\n return storageCache.get(key)\n}\n\nfunction setLocalStorage(key: string, value: string) {\n localStorage.setItem(key, value)\n storageCache.set(key, value) // keep cache in sync\n}",
"language": "typescript",
"description": "Map cache"
},
{
"ruleId": "",
"ruleTitle": "Combine Multiple Array Iterations",
"type": "bad",
"code": "const admins = users.filter(u => u.isAdmin)\nconst testers = users.filter(u => u.isTester)\nconst inactive = users.filter(u => !u.isActive)",
"language": "typescript",
"description": "3 iterations"
},
{
"ruleId": "",
"ruleTitle": "Combine Multiple Array Iterations",
"type": "good",
"code": "const admins: User[] = []\nconst testers: User[] = []\nconst inactive: User[] = []\n\nfor (const user of users) {\n if (user.isAdmin) admins.push(user)\n if (user.isTester) testers.push(user)\n if (!user.isActive) inactive.push(user)\n}",
"language": "typescript",
"description": "1 iteration"
},
{
"ruleId": "",
"ruleTitle": "Early Return from Functions",
"type": "bad",
"code": "function validateUsers(users: User[]) {\n let hasError = false\n let errorMessage = ''\n \n for (const user of users) {\n if (!user.email) {\n hasError = true\n errorMessage = 'Email required'\n }\n if (!user.name) {\n hasError = true\n errorMessage = 'Name required'\n }\n // Continues checking all users even after error found\n }\n \n return hasError ? { valid: false, error: errorMessage } : { valid: true }\n}",
"language": "typescript",
"description": "processes all items even after finding answer"
},
{
"ruleId": "",
"ruleTitle": "Early Return from Functions",
"type": "good",
"code": "function validateUsers(users: User[]) {\n for (const user of users) {\n if (!user.email) {\n return { valid: false, error: 'Email required' }\n }\n if (!user.name) {\n return { valid: false, error: 'Name required' }\n }\n }\n\n return { valid: true }\n}",
"language": "typescript",
"description": "returns immediately on first error"
},
{
"ruleId": "",
"ruleTitle": "Use flatMap to Map and Filter in One Pass",
"type": "bad",
"code": "const userNames = users\n .map(user => user.isActive ? user.name : null)\n .filter(Boolean)",
"language": "typescript",
"description": "2 iterations, intermediate array"
},
{
"ruleId": "",
"ruleTitle": "Use flatMap to Map and Filter in One Pass",
"type": "good",
"code": "const userNames = users.flatMap(user =>\n user.isActive ? [user.name] : []\n)",
"language": "typescript",
"description": "1 iteration, no intermediate array"
},
{
"ruleId": "",
"ruleTitle": "Hoist RegExp Creation",
"type": "bad",
"code": "function Highlighter({ text, query }: Props) {\n const regex = new RegExp(`(${query})`, 'gi')\n const parts = text.split(regex)\n return <>{parts.map((part, i) => ...)}>\n}",
"language": "tsx",
"description": "new RegExp every render"
},
{
"ruleId": "",
"ruleTitle": "Hoist RegExp Creation",
"type": "good",
"code": "const EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nfunction Highlighter({ text, query }: Props) {\n const regex = useMemo(\n () => new RegExp(`(${escapeRegex(query)})`, 'gi'),\n [query]\n )\n const parts = text.split(regex)\n return <>{parts.map((part, i) => ...)}>\n}",
"language": "tsx",
"description": "memoize or hoist"
},
{
"ruleId": "",
"ruleTitle": "Build Index Maps for Repeated Lookups",
"type": "bad",
"code": "function processOrders(orders: Order[], users: User[]) {\n return orders.map(order => ({\n ...order,\n user: users.find(u => u.id === order.userId)\n }))\n}",
"language": "typescript",
"description": "Incorrect (O(n) per lookup) example for Build Index Maps for Repeated Lookups"
},
{
"ruleId": "",
"ruleTitle": "Build Index Maps for Repeated Lookups",
"type": "good",
"code": "function processOrders(orders: Order[], users: User[]) {\n const userById = new Map(users.map(u => [u.id, u]))\n\n return orders.map(order => ({\n ...order,\n user: userById.get(order.userId)\n }))\n}",
"language": "typescript",
"description": "Correct (O(1) per lookup) example for Build Index Maps for Repeated Lookups"
},
{
"ruleId": "",
"ruleTitle": "Early Length Check for Array Comparisons",
"type": "bad",
"code": "function hasChanges(current: string[], original: string[]) {\n // Always sorts and joins, even when lengths differ\n return current.sort().join() !== original.sort().join()\n}",
"language": "typescript",
"description": "always runs expensive comparison"
},
{
"ruleId": "",
"ruleTitle": "Early Length Check for Array Comparisons",
"type": "good",
"code": "function hasChanges(current: string[], original: string[]) {\n // Early return if lengths differ\n if (current.length !== original.length) {\n return true\n }\n // Only sort when lengths match\n const currentSorted = current.toSorted()\n const originalSorted = original.toSorted()\n for (let i = 0; i < currentSorted.length; i++) {\n if (currentSorted[i] !== originalSorted[i]) {\n return true\n }\n }\n return false\n}",
"language": "typescript",
"description": "Correct (O(1) length check first) example for Early Length Check for Array Comparisons"
},
{
"ruleId": "",
"ruleTitle": "Use Loop for Min/Max Instead of Sort",
"type": "bad",
"code": "interface Project {\n id: string\n name: string\n updatedAt: number\n}\n\nfunction getLatestProject(projects: Project[]) {\n const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)\n return sorted[0]\n}",
"language": "typescript",
"description": "Incorrect (O(n log n) - sort to find latest) example for Use Loop for Min/Max Instead of Sort"
},
{
"ruleId": "",
"ruleTitle": "Use Loop for Min/Max Instead of Sort",
"type": "bad",
"code": "function getOldestAndNewest(projects: Project[]) {\n const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)\n return { oldest: sorted[0], newest: sorted[sorted.length - 1] }\n}",
"language": "typescript",
"description": "Incorrect (O(n log n) - sort for oldest and newest) example for Use Loop for Min/Max Instead of Sort"
},
{
"ruleId": "",
"ruleTitle": "Use Loop for Min/Max Instead of Sort",
"type": "good",
"code": "function getLatestProject(projects: Project[]) {\n if (projects.length === 0) return null\n \n let latest = projects[0]\n \n for (let i = 1; i < projects.length; i++) {\n if (projects[i].updatedAt > latest.updatedAt) {\n latest = projects[i]\n }\n }\n \n return latest\n}\n\nfunction getOldestAndNewest(projects: Project[]) {\n if (projects.length === 0) return { oldest: null, newest: null }\n \n let oldest = projects[0]\n let newest = projects[0]\n \n for (let i = 1; i < projects.length; i++) {\n if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]\n if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]\n }\n \n return { oldest, newest }\n}",
"language": "typescript",
"description": "Correct (O(n) - single loop) example for Use Loop for Min/Max Instead of Sort"
},
{
"ruleId": "",
"ruleTitle": "Defer Non-Critical Work with requestIdleCallback",
"type": "bad",
"code": "function handleSearch(query: string) {\n const results = searchItems(query)\n setResults(results)\n\n // These block the main thread immediately\n analytics.track('search', { query })\n saveToRecentSearches(query)\n prefetchTopResults(results.slice(0, 3))\n}",
"language": "typescript",
"description": "blocks main thread during user interaction"
},
{
"ruleId": "",
"ruleTitle": "Defer Non-Critical Work with requestIdleCallback",
"type": "good",
"code": "function handleSearch(query: string) {\n const results = searchItems(query)\n setResults(results)\n\n // Defer non-critical work to idle periods\n requestIdleCallback(() => {\n analytics.track('search', { query })\n })\n\n requestIdleCallback(() => {\n saveToRecentSearches(query)\n })\n\n requestIdleCallback(() => {\n prefetchTopResults(results.slice(0, 3))\n })\n}",
"language": "typescript",
"description": "defers non-critical work to idle time"
},
{
"ruleId": "",
"ruleTitle": "Use Set/Map for O(1) Lookups",
"type": "bad",
"code": "const allowedIds = ['a', 'b', 'c', ...]\nitems.filter(item => allowedIds.includes(item.id))",
"language": "typescript",
"description": "Incorrect (O(n) per check) example for Use Set/Map for O(1) Lookups"
},
{
"ruleId": "",
"ruleTitle": "Use Set/Map for O(1) Lookups",
"type": "good",
"code": "const allowedIds = new Set(['a', 'b', 'c', ...])\nitems.filter(item => allowedIds.has(item.id))",
"language": "typescript",
"description": "Correct (O(1) per check) example for Use Set/Map for O(1) Lookups"
},
{
"ruleId": "",
"ruleTitle": "Use toSorted() Instead of sort() for Immutability",
"type": "bad",
"code": "function UserList({ users }: { users: User[] }) {\n // Mutates the users prop array!\n const sorted = useMemo(\n () => users.sort((a, b) => a.name.localeCompare(b.name)),\n [users]\n )\n return {sorted.map(renderUser)}
\n}",
"language": "typescript",
"description": "mutates original array"
},
{
"ruleId": "",
"ruleTitle": "Use toSorted() Instead of sort() for Immutability",
"type": "good",
"code": "function UserList({ users }: { users: User[] }) {\n // Creates new sorted array, original unchanged\n const sorted = useMemo(\n () => users.toSorted((a, b) => a.name.localeCompare(b.name)),\n [users]\n )\n return {sorted.map(renderUser)}
\n}",
"language": "typescript",
"description": "creates new array"
},
{
"ruleId": "",
"ruleTitle": "Animate SVG Wrapper Instead of SVG Element",
"type": "bad",
"code": "function LoadingSpinner() {\n return (\n \n )\n}",
"language": "tsx",
"description": "animating SVG directly - no hardware acceleration"
},
{
"ruleId": "",
"ruleTitle": "Animate SVG Wrapper Instead of SVG Element",
"type": "good",
"code": "function LoadingSpinner() {\n return (\n \n \n
\n )\n}",
"language": "tsx",
"description": "animating wrapper div - hardware accelerated"
},
{
"ruleId": "",
"ruleTitle": "Use Explicit Conditional Rendering",
"type": "bad",
"code": "function Badge({ count }: { count: number }) {\n return (\n \n {count && {count}}\n
\n )\n}\n\n// When count = 0, renders: 0
\n// When count = 5, renders: 5
",
"language": "tsx",
"description": "renders \"0\" when count is 0"
},
{
"ruleId": "",
"ruleTitle": "Use Explicit Conditional Rendering",
"type": "good",
"code": "function Badge({ count }: { count: number }) {\n return (\n \n {count > 0 ? {count} : null}\n
\n )\n}\n\n// When count = 0, renders: \n// When count = 5, renders: 5
",
"language": "tsx",
"description": "renders nothing when count is 0"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static JSX Elements",
"type": "bad",
"code": "function LoadingSkeleton() {\n return \n}\n\nfunction Container() {\n return (\n \n {loading && }\n
\n )\n}",
"language": "tsx",
"description": "recreates element every render"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static JSX Elements",
"type": "good",
"code": "const loadingSkeleton = (\n \n)\n\nfunction Container() {\n return (\n \n {loading && loadingSkeleton}\n
\n )\n}",
"language": "tsx",
"description": "reuses same element"
},
{
"ruleId": "",
"ruleTitle": "Prevent Hydration Mismatch Without Flickering",
"type": "bad",
"code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n // localStorage is not available on server - throws error\n const theme = localStorage.getItem('theme') || 'light'\n \n return (\n \n {children}\n
\n )\n}",
"language": "tsx",
"description": "breaks SSR"
},
{
"ruleId": "",
"ruleTitle": "Prevent Hydration Mismatch Without Flickering",
"type": "bad",
"code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n const [theme, setTheme] = useState('light')\n \n useEffect(() => {\n // Runs after hydration - causes visible flash\n const stored = localStorage.getItem('theme')\n if (stored) {\n setTheme(stored)\n }\n }, [])\n \n return (\n \n {children}\n
\n )\n}",
"language": "tsx",
"description": "visual flickering"
},
{
"ruleId": "",
"ruleTitle": "Prevent Hydration Mismatch Without Flickering",
"type": "good",
"code": "function ThemeWrapper({ children }: { children: ReactNode }) {\n return (\n <>\n \n {children}\n
\n \n >\n )\n}",
"language": "tsx",
"description": "no flicker, no hydration mismatch"
},
{
"ruleId": "",
"ruleTitle": "Suppress Expected Hydration Mismatches",
"type": "bad",
"code": "function Timestamp() {\n return {new Date().toLocaleString()}\n}",
"language": "tsx",
"description": "known mismatch warnings"
},
{
"ruleId": "",
"ruleTitle": "Suppress Expected Hydration Mismatches",
"type": "good",
"code": "function Timestamp() {\n return (\n \n {new Date().toLocaleString()}\n \n )\n}",
"language": "tsx",
"description": "suppress expected mismatch only"
},
{
"ruleId": "",
"ruleTitle": "Use defer or async on Script Tags",
"type": "bad",
"code": "export default function Document() {\n return (\n \n \n \n \n \n {/* content */}\n \n )\n}",
"language": "tsx",
"description": "blocks rendering"
},
{
"ruleId": "",
"ruleTitle": "Use defer or async on Script Tags",
"type": "good",
"code": "import Script from 'next/script'\n\nexport default function Page() {\n return (\n <>\n \n \n >\n )\n}",
"language": "tsx",
"description": "non-blocking"
},
{
"ruleId": "",
"ruleTitle": "Optimize SVG Precision",
"type": "bad",
"code": "",
"language": "svg",
"description": "excessive precision"
},
{
"ruleId": "",
"ruleTitle": "Optimize SVG Precision",
"type": "good",
"code": "",
"language": "svg",
"description": "1 decimal place"
},
{
"ruleId": "",
"ruleTitle": "Use useTransition Over Manual Loading States",
"type": "bad",
"code": "function SearchResults() {\n const [query, setQuery] = useState('')\n const [results, setResults] = useState([])\n const [isLoading, setIsLoading] = useState(false)\n\n const handleSearch = async (value: string) => {\n setIsLoading(true)\n setQuery(value)\n const data = await fetchResults(value)\n setResults(data)\n setIsLoading(false)\n }\n\n return (\n <>\n handleSearch(e.target.value)} />\n {isLoading && }\n \n >\n )\n}",
"language": "tsx",
"description": "manual loading state"
},
{
"ruleId": "",
"ruleTitle": "Use useTransition Over Manual Loading States",
"type": "good",
"code": "import { useTransition, useState } from 'react'\n\nfunction SearchResults() {\n const [query, setQuery] = useState('')\n const [results, setResults] = useState([])\n const [isPending, startTransition] = useTransition()\n\n const handleSearch = (value: string) => {\n setQuery(value) // Update input immediately\n \n startTransition(async () => {\n // Fetch and update results\n const data = await fetchResults(value)\n setResults(data)\n })\n }\n\n return (\n <>\n handleSearch(e.target.value)} />\n {isPending && }\n \n >\n )\n}",
"language": "tsx",
"description": "useTransition with built-in pending state"
},
{
"ruleId": "",
"ruleTitle": "Defer State Reads to Usage Point",
"type": "bad",
"code": "function ShareButton({ chatId }: { chatId: string }) {\n const searchParams = useSearchParams()\n\n const handleShare = () => {\n const ref = searchParams.get('ref')\n shareChat(chatId, { ref })\n }\n\n return \n}",
"language": "tsx",
"description": "subscribes to all searchParams changes"
},
{
"ruleId": "",
"ruleTitle": "Defer State Reads to Usage Point",
"type": "good",
"code": "function ShareButton({ chatId }: { chatId: string }) {\n const handleShare = () => {\n const params = new URLSearchParams(window.location.search)\n const ref = params.get('ref')\n shareChat(chatId, { ref })\n }\n\n return \n}",
"language": "tsx",
"description": "reads on demand, no subscription"
},
{
"ruleId": "",
"ruleTitle": "Narrow Effect Dependencies",
"type": "bad",
"code": "useEffect(() => {\n console.log(user.id)\n}, [user])",
"language": "tsx",
"description": "re-runs on any user field change"
},
{
"ruleId": "",
"ruleTitle": "Narrow Effect Dependencies",
"type": "good",
"code": "useEffect(() => {\n console.log(user.id)\n}, [user.id])",
"language": "tsx",
"description": "re-runs only when id changes"
},
{
"ruleId": "",
"ruleTitle": "Calculate Derived State During Rendering",
"type": "bad",
"code": "function Form() {\n const [firstName, setFirstName] = useState('First')\n const [lastName, setLastName] = useState('Last')\n const [fullName, setFullName] = useState('')\n\n useEffect(() => {\n setFullName(firstName + ' ' + lastName)\n }, [firstName, lastName])\n\n return {fullName}
\n}",
"language": "tsx",
"description": "redundant state and effect"
},
{
"ruleId": "",
"ruleTitle": "Calculate Derived State During Rendering",
"type": "good",
"code": "function Form() {\n const [firstName, setFirstName] = useState('First')\n const [lastName, setLastName] = useState('Last')\n const fullName = firstName + ' ' + lastName\n\n return {fullName}
\n}",
"language": "tsx",
"description": "derive during render"
},
{
"ruleId": "",
"ruleTitle": "Subscribe to Derived State",
"type": "bad",
"code": "function Sidebar() {\n const width = useWindowWidth() // updates continuously\n const isMobile = width < 768\n return \n}",
"language": "tsx",
"description": "re-renders on every pixel change"
},
{
"ruleId": "",
"ruleTitle": "Subscribe to Derived State",
"type": "good",
"code": "function Sidebar() {\n const isMobile = useMediaQuery('(max-width: 767px)')\n return \n}",
"language": "tsx",
"description": "re-renders only when boolean changes"
},
{
"ruleId": "",
"ruleTitle": "Use Functional setState Updates",
"type": "bad",
"code": "function TodoList() {\n const [items, setItems] = useState(initialItems)\n \n // Callback must depend on items, recreated on every items change\n const addItems = useCallback((newItems: Item[]) => {\n setItems([...items, ...newItems])\n }, [items]) // ❌ items dependency causes recreations\n \n // Risk of stale closure if dependency is forgotten\n const removeItem = useCallback((id: string) => {\n setItems(items.filter(item => item.id !== id))\n }, []) // ❌ Missing items dependency - will use stale items!\n \n return \n}",
"language": "tsx",
"description": "requires state as dependency"
},
{
"ruleId": "",
"ruleTitle": "Use Functional setState Updates",
"type": "good",
"code": "function TodoList() {\n const [items, setItems] = useState(initialItems)\n \n // Stable callback, never recreated\n const addItems = useCallback((newItems: Item[]) => {\n setItems(curr => [...curr, ...newItems])\n }, []) // ✅ No dependencies needed\n \n // Always uses latest state, no stale closure risk\n const removeItem = useCallback((id: string) => {\n setItems(curr => curr.filter(item => item.id !== id))\n }, []) // ✅ Safe and stable\n \n return \n}",
"language": "tsx",
"description": "stable callbacks, no stale closures"
},
{
"ruleId": "",
"ruleTitle": "Use Lazy State Initialization",
"type": "bad",
"code": "function FilteredList({ items }: { items: Item[] }) {\n // buildSearchIndex() runs on EVERY render, even after initialization\n const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))\n const [query, setQuery] = useState('')\n \n // When query changes, buildSearchIndex runs again unnecessarily\n return \n}\n\nfunction UserProfile() {\n // JSON.parse runs on every render\n const [settings, setSettings] = useState(\n JSON.parse(localStorage.getItem('settings') || '{}')\n )\n \n return \n}",
"language": "tsx",
"description": "runs on every render"
},
{
"ruleId": "",
"ruleTitle": "Use Lazy State Initialization",
"type": "good",
"code": "function FilteredList({ items }: { items: Item[] }) {\n // buildSearchIndex() runs ONLY on initial render\n const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))\n const [query, setQuery] = useState('')\n \n return \n}\n\nfunction UserProfile() {\n // JSON.parse runs only on initial render\n const [settings, setSettings] = useState(() => {\n const stored = localStorage.getItem('settings')\n return stored ? JSON.parse(stored) : {}\n })\n \n return \n}",
"language": "tsx",
"description": "runs only once"
},
{
"ruleId": "",
"ruleTitle": "Extract Default Non-primitive Parameter Value from Memoized Component to Constant",
"type": "bad",
"code": "const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {\n // ...\n})\n\n// Used without optional onClick\n",
"language": "tsx",
"description": "`onClick` has different values on every rerender"
},
{
"ruleId": "",
"ruleTitle": "Extract Default Non-primitive Parameter Value from Memoized Component to Constant",
"type": "good",
"code": "const NOOP = () => {};\n\nconst UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {\n // ...\n})\n\n// Used without optional onClick\n",
"language": "tsx",
"description": "stable default value"
},
{
"ruleId": "",
"ruleTitle": "Extract to Memoized Components",
"type": "bad",
"code": "function Profile({ user, loading }: Props) {\n const avatar = useMemo(() => {\n const id = computeAvatarId(user)\n return \n }, [user])\n\n if (loading) return \n return {avatar}
\n}",
"language": "tsx",
"description": "computes avatar even when loading"
},
{
"ruleId": "",
"ruleTitle": "Extract to Memoized Components",
"type": "good",
"code": "const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {\n const id = useMemo(() => computeAvatarId(user), [user])\n return \n})\n\nfunction Profile({ user, loading }: Props) {\n if (loading) return \n return (\n \n \n
\n )\n}",
"language": "tsx",
"description": "skips computation when loading"
},
{
"ruleId": "",
"ruleTitle": "Put Interaction Logic in Event Handlers",
"type": "bad",
"code": "function Form() {\n const [submitted, setSubmitted] = useState(false)\n const theme = useContext(ThemeContext)\n\n useEffect(() => {\n if (submitted) {\n post('/api/register')\n showToast('Registered', theme)\n }\n }, [submitted, theme])\n\n return \n}",
"language": "tsx",
"description": "event modeled as state + effect"
},
{
"ruleId": "",
"ruleTitle": "Put Interaction Logic in Event Handlers",
"type": "good",
"code": "function Form() {\n const theme = useContext(ThemeContext)\n\n function handleSubmit() {\n post('/api/register')\n showToast('Registered', theme)\n }\n\n return \n}",
"language": "tsx",
"description": "do it in the handler"
},
{
"ruleId": "",
"ruleTitle": "Don't Define Components Inside Components",
"type": "bad",
"code": "function UserProfile({ user, theme }) {\n // Defined inside to access `theme` - BAD\n const Avatar = () => (\n
\n )\n\n // Defined inside to access `user` - BAD\n const Stats = () => (\n \n {user.followers} followers\n {user.posts} posts\n
\n )\n\n return (\n \n )\n}",
"language": "tsx",
"description": "remounts on every render"
},
{
"ruleId": "",
"ruleTitle": "Don't Define Components Inside Components",
"type": "good",
"code": "function Avatar({ src, theme }: { src: string; theme: string }) {\n return (\n
\n )\n}\n\nfunction Stats({ followers, posts }: { followers: number; posts: number }) {\n return (\n \n {followers} followers\n {posts} posts\n
\n )\n}\n\nfunction UserProfile({ user, theme }) {\n return (\n \n )\n}",
"language": "tsx",
"description": "pass props instead"
},
{
"ruleId": "",
"ruleTitle": "Do not wrap a simple expression with a primitive result type in useMemo",
"type": "bad",
"code": "function Header({ user, notifications }: Props) {\n const isLoading = useMemo(() => {\n return user.isLoading || notifications.isLoading\n }, [user.isLoading, notifications.isLoading])\n\n if (isLoading) return \n // return some markup\n}",
"language": "tsx",
"description": "Incorrect example for Do not wrap a simple expression with a primitive result type in useMemo"
},
{
"ruleId": "",
"ruleTitle": "Do not wrap a simple expression with a primitive result type in useMemo",
"type": "good",
"code": "function Header({ user, notifications }: Props) {\n const isLoading = user.isLoading || notifications.isLoading\n\n if (isLoading) return \n // return some markup\n}",
"language": "tsx",
"description": "Correct example for Do not wrap a simple expression with a primitive result type in useMemo"
},
{
"ruleId": "",
"ruleTitle": "Split Combined Hook Computations",
"type": "bad",
"code": "const sortedProducts = useMemo(() => {\n const filtered = products.filter((p) => p.category === category)\n const sorted = filtered.toSorted((a, b) =>\n sortOrder === \"asc\" ? a.price - b.price : b.price - a.price\n )\n return sorted\n}, [products, category, sortOrder])",
"language": "tsx",
"description": "changing `sortOrder` recomputes filtering"
},
{
"ruleId": "",
"ruleTitle": "Split Combined Hook Computations",
"type": "good",
"code": "const filteredProducts = useMemo(\n () => products.filter((p) => p.category === category),\n [products, category]\n)\n\nconst sortedProducts = useMemo(\n () =>\n filteredProducts.toSorted((a, b) =>\n sortOrder === \"asc\" ? a.price - b.price : b.price - a.price\n ),\n [filteredProducts, sortOrder]\n)",
"language": "tsx",
"description": "filtering only recomputes when products or category change"
},
{
"ruleId": "",
"ruleTitle": "Split Combined Hook Computations",
"type": "bad",
"code": "useEffect(() => {\n analytics.trackPageView(pathname)\n document.title = `${pageTitle} | My App`\n}, [pathname, pageTitle])",
"language": "tsx",
"description": "both effects run when either dependency changes"
},
{
"ruleId": "",
"ruleTitle": "Split Combined Hook Computations",
"type": "good",
"code": "useEffect(() => {\n analytics.trackPageView(pathname)\n}, [pathname])\n\nuseEffect(() => {\n document.title = `${pageTitle} | My App`\n}, [pageTitle])",
"language": "tsx",
"description": "effects run independently"
},
{
"ruleId": "",
"ruleTitle": "Use Transitions for Non-Urgent Updates",
"type": "bad",
"code": "function ScrollTracker() {\n const [scrollY, setScrollY] = useState(0)\n useEffect(() => {\n const handler = () => setScrollY(window.scrollY)\n window.addEventListener('scroll', handler, { passive: true })\n return () => window.removeEventListener('scroll', handler)\n }, [])\n}",
"language": "tsx",
"description": "blocks UI on every scroll"
},
{
"ruleId": "",
"ruleTitle": "Use Transitions for Non-Urgent Updates",
"type": "good",
"code": "import { startTransition } from 'react'\n\nfunction ScrollTracker() {\n const [scrollY, setScrollY] = useState(0)\n useEffect(() => {\n const handler = () => {\n startTransition(() => setScrollY(window.scrollY))\n }\n window.addEventListener('scroll', handler, { passive: true })\n return () => window.removeEventListener('scroll', handler)\n }, [])\n}",
"language": "tsx",
"description": "non-blocking updates"
},
{
"ruleId": "",
"ruleTitle": "Use useDeferredValue for Expensive Derived Renders",
"type": "bad",
"code": "function Search({ items }: { items: Item[] }) {\n const [query, setQuery] = useState('')\n const filtered = items.filter(item => fuzzyMatch(item, query))\n\n return (\n <>\n setQuery(e.target.value)} />\n \n >\n )\n}",
"language": "tsx",
"description": "input feels laggy while filtering"
},
{
"ruleId": "",
"ruleTitle": "Use useDeferredValue for Expensive Derived Renders",
"type": "good",
"code": "function Search({ items }: { items: Item[] }) {\n const [query, setQuery] = useState('')\n const deferredQuery = useDeferredValue(query)\n const filtered = useMemo(\n () => items.filter(item => fuzzyMatch(item, deferredQuery)),\n [items, deferredQuery]\n )\n const isStale = query !== deferredQuery\n\n return (\n <>\n setQuery(e.target.value)} />\n \n \n
\n >\n )\n}",
"language": "tsx",
"description": "input stays snappy, results render when ready"
},
{
"ruleId": "",
"ruleTitle": "Use useRef for Transient Values",
"type": "bad",
"code": "function Tracker() {\n const [lastX, setLastX] = useState(0)\n\n useEffect(() => {\n const onMove = (e: MouseEvent) => setLastX(e.clientX)\n window.addEventListener('mousemove', onMove)\n return () => window.removeEventListener('mousemove', onMove)\n }, [])\n\n return (\n \n )\n}",
"language": "tsx",
"description": "renders every update"
},
{
"ruleId": "",
"ruleTitle": "Use useRef for Transient Values",
"type": "good",
"code": "function Tracker() {\n const lastXRef = useRef(0)\n const dotRef = useRef(null)\n\n useEffect(() => {\n const onMove = (e: MouseEvent) => {\n lastXRef.current = e.clientX\n const node = dotRef.current\n if (node) {\n node.style.transform = `translateX(${e.clientX}px)`\n }\n }\n window.addEventListener('mousemove', onMove)\n return () => window.removeEventListener('mousemove', onMove)\n }, [])\n\n return (\n \n )\n}",
"language": "tsx",
"description": "no re-render for tracking"
},
{
"ruleId": "",
"ruleTitle": "Use after() for Non-Blocking Operations",
"type": "bad",
"code": "import { logUserAction } from '@/app/utils'\n\nexport async function POST(request: Request) {\n // Perform mutation\n await updateDatabase(request)\n \n // Logging blocks the response\n const userAgent = request.headers.get('user-agent') || 'unknown'\n await logUserAction({ userAgent })\n \n return new Response(JSON.stringify({ status: 'success' }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' }\n })\n}",
"language": "tsx",
"description": "blocks response"
},
{
"ruleId": "",
"ruleTitle": "Use after() for Non-Blocking Operations",
"type": "good",
"code": "import { after } from 'next/server'\nimport { headers, cookies } from 'next/headers'\nimport { logUserAction } from '@/app/utils'\n\nexport async function POST(request: Request) {\n // Perform mutation\n await updateDatabase(request)\n \n // Log after response is sent\n after(async () => {\n const userAgent = (await headers()).get('user-agent') || 'unknown'\n const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'\n \n logUserAction({ sessionCookie, userAgent })\n })\n \n return new Response(JSON.stringify({ status: 'success' }), {\n status: 200,\n headers: { 'Content-Type': 'application/json' }\n })\n}",
"language": "tsx",
"description": "non-blocking"
},
{
"ruleId": "",
"ruleTitle": "Authenticate Server Actions Like API Routes",
"type": "bad",
"code": "'use server'\n\nexport async function deleteUser(userId: string) {\n // Anyone can call this! No auth check\n await db.user.delete({ where: { id: userId } })\n return { success: true }\n}",
"language": "typescript",
"description": "no authentication check"
},
{
"ruleId": "",
"ruleTitle": "Authenticate Server Actions Like API Routes",
"type": "good",
"code": "'use server'\n\nimport { verifySession } from '@/lib/auth'\nimport { unauthorized } from '@/lib/errors'\n\nexport async function deleteUser(userId: string) {\n // Always check auth inside the action\n const session = await verifySession()\n \n if (!session) {\n throw unauthorized('Must be logged in')\n }\n \n // Check authorization too\n if (session.user.role !== 'admin' && session.user.id !== userId) {\n throw unauthorized('Cannot delete other users')\n }\n \n await db.user.delete({ where: { id: userId } })\n return { success: true }\n}",
"language": "typescript",
"description": "authentication inside the action"
},
{
"ruleId": "",
"ruleTitle": "Per-Request Deduplication with React.cache()",
"type": "bad",
"code": "const getUser = cache(async (params: { uid: number }) => {\n return await db.user.findUnique({ where: { id: params.uid } })\n})\n\n// Each call creates new object, never hits cache\ngetUser({ uid: 1 })\ngetUser({ uid: 1 }) // Cache miss, runs query again",
"language": "typescript",
"description": "always cache miss"
},
{
"ruleId": "",
"ruleTitle": "Per-Request Deduplication with React.cache()",
"type": "good",
"code": "const params = { uid: 1 }\ngetUser(params) // Query runs\ngetUser(params) // Cache hit (same reference)",
"language": "typescript",
"description": "cache hit"
},
{
"ruleId": "",
"ruleTitle": "Avoid Duplicate Serialization in RSC Props",
"type": "bad",
"code": "// RSC: sends 6 strings (2 arrays × 3 items)\n",
"language": "tsx",
"description": "duplicates array"
},
{
"ruleId": "",
"ruleTitle": "Avoid Duplicate Serialization in RSC Props",
"type": "good",
"code": "// RSC: send once\n\n\n// Client: transform there\n'use client'\nconst sorted = useMemo(() => [...usernames].sort(), [usernames])",
"language": "tsx",
"description": "sends 3 strings"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static I/O to Module Level",
"type": "bad",
"code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\n\nexport async function GET(request: Request) {\n // Runs on EVERY request - expensive!\n const fontData = await fetch(\n new URL('./fonts/Inter.ttf', import.meta.url)\n ).then(res => res.arrayBuffer())\n\n const logoData = await fetch(\n new URL('./images/logo.png', import.meta.url)\n ).then(res => res.arrayBuffer())\n\n return new ImageResponse(\n \n

\n Hello World\n
,\n { fonts: [{ name: 'Inter', data: fontData }] }\n )\n}",
"language": "typescript",
"description": "reads font file on every request"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static I/O to Module Level",
"type": "good",
"code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\n\n// Module-level: runs ONCE when module is first imported\nconst fontData = fetch(\n new URL('./fonts/Inter.ttf', import.meta.url)\n).then(res => res.arrayBuffer())\n\nconst logoData = fetch(\n new URL('./images/logo.png', import.meta.url)\n).then(res => res.arrayBuffer())\n\nexport async function GET(request: Request) {\n // Await the already-started promises\n const [font, logo] = await Promise.all([fontData, logoData])\n\n return new ImageResponse(\n \n

\n Hello World\n
,\n { fonts: [{ name: 'Inter', data: font }] }\n )\n}",
"language": "typescript",
"description": "loads once at module initialization"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static I/O to Module Level",
"type": "good",
"code": "// app/api/og/route.tsx\nimport { ImageResponse } from 'next/og'\nimport { readFileSync } from 'fs'\nimport { join } from 'path'\n\n// Synchronous read at module level - blocks only during module init\nconst fontData = readFileSync(\n join(process.cwd(), 'public/fonts/Inter.ttf')\n)\n\nconst logoData = readFileSync(\n join(process.cwd(), 'public/images/logo.png')\n)\n\nexport async function GET(request: Request) {\n return new ImageResponse(\n \n

\n Hello World\n
,\n { fonts: [{ name: 'Inter', data: fontData }] }\n )\n}",
"language": "typescript",
"description": "synchronous fs at module level"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static I/O to Module Level",
"type": "bad",
"code": "import fs from 'node:fs/promises'\n\nexport async function processRequest(data: Data) {\n const config = JSON.parse(\n await fs.readFile('./config.json', 'utf-8')\n )\n const template = await fs.readFile('./template.html', 'utf-8')\n\n return render(template, data, config)\n}",
"language": "typescript",
"description": "reads config on every call"
},
{
"ruleId": "",
"ruleTitle": "Hoist Static I/O to Module Level",
"type": "good",
"code": "import fs from 'node:fs/promises'\n\nconst configPromise = fs\n .readFile('./config.json', 'utf-8')\n .then(JSON.parse)\nconst templatePromise = fs.readFile('./template.html', 'utf-8')\n\nexport async function processRequest(data: Data) {\n const [config, template] = await Promise.all([\n configPromise,\n templatePromise,\n ])\n\n return render(template, data, config)\n}",
"language": "typescript",
"description": "hoists config and template to module level"
},
{
"ruleId": "",
"ruleTitle": "Avoid Shared Module State for Request Data",
"type": "bad",
"code": "let currentUser: User | null = null\n\nexport default async function Page() {\n currentUser = await auth()\n return \n}\n\nasync function Dashboard() {\n return {currentUser?.name}
\n}",
"language": "tsx",
"description": "request data leaks across concurrent renders"
},
{
"ruleId": "",
"ruleTitle": "Avoid Shared Module State for Request Data",
"type": "good",
"code": "export default async function Page() {\n const user = await auth()\n return \n}\n\nfunction Dashboard({ user }: { user: User | null }) {\n return {user?.name}
\n}",
"language": "tsx",
"description": "keep request data local to the render tree"
},
{
"ruleId": "",
"ruleTitle": "Parallel Data Fetching with Component Composition",
"type": "bad",
"code": "export default async function Page() {\n const header = await fetchHeader()\n return (\n \n )\n}\n\nasync function Sidebar() {\n const items = await fetchSidebarItems()\n return \n}",
"language": "tsx",
"description": "Sidebar waits for Page's fetch to complete"
},
{
"ruleId": "",
"ruleTitle": "Parallel Data Fetching with Component Composition",
"type": "good",
"code": "async function Header() {\n const data = await fetchHeader()\n return {data}
\n}\n\nasync function Sidebar() {\n const items = await fetchSidebarItems()\n return \n}\n\nexport default function Page() {\n return (\n \n \n \n
\n )\n}",
"language": "tsx",
"description": "both fetch simultaneously"
},
{
"ruleId": "",
"ruleTitle": "Parallel Nested Data Fetching",
"type": "bad",
"code": "const chats = await Promise.all(\n chatIds.map(id => getChat(id))\n)\n\nconst chatAuthors = await Promise.all(\n chats.map(chat => getUser(chat.author))\n)",
"language": "tsx",
"description": "a single slow item blocks all nested fetches"
},
{
"ruleId": "",
"ruleTitle": "Parallel Nested Data Fetching",
"type": "good",
"code": "const chatAuthors = await Promise.all(\n chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))\n)",
"language": "tsx",
"description": "each item chains its own nested fetch"
},
{
"ruleId": "",
"ruleTitle": "Minimize Serialization at RSC Boundaries",
"type": "bad",
"code": "async function Page() {\n const user = await fetchUser() // 50 fields\n return \n}\n\n'use client'\nfunction Profile({ user }: { user: User }) {\n return {user.name}
// uses 1 field\n}",
"language": "tsx",
"description": "serializes all 50 fields"
},
{
"ruleId": "",
"ruleTitle": "Minimize Serialization at RSC Boundaries",
"type": "good",
"code": "async function Page() {\n const user = await fetchUser()\n return \n}\n\n'use client'\nfunction Profile({ name }: { name: string }) {\n return {name}
\n}",
"language": "tsx",
"description": "serializes only 1 field"
}
]