AGENTS.md · 72000
ation)**
Extract static JSX outside components to avoid re-creation.
Incorrect: recreates element every render
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
Correct: reuses same element
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
Note: If your project has React Compiler enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
6.4 Optimize SVG Precision
Impact: LOW (reduces file size)
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
Incorrect: excessive precision
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
Correct: 1 decimal place
<path d="M 10.3 20.8 L 30.9 40.2" />
Automate with SVGO:
npx svgo --precision=1 --multipass icon.svg
6.5 Prevent Hydration Mismatch Without Flickering
Impact: MEDIUM (avoids visual flicker and hydration errors)
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
Incorrect: breaks SSR
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
Server-side rendering will fail because localStorage is undefined.
Incorrect: visual flickering
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
Component first renders with default value (light), then updates after hydration, causing a visible flash of incorrect content.
Correct: no flicker, no hydration mismatch
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
6.6 Suppress Expected Hydration Mismatches
Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these expected mismatches, wrap the dynamic text in an element with suppressHydrationWarning to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
Incorrect: known mismatch warnings
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
Correct: suppress expected mismatch only
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
6.7 Use Activity Component for Show/Hide
Impact: MEDIUM (preserves state/DOM)
Use React's <Activity> to preserve state/DOM for expensive components that frequently toggle visibility.
Usage:
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
Avoids expensive re-renders and state loss.
6.8 Use defer or async on Script Tags
Impact: HIGH (eliminates render-blocking)
Script tags without defer or async block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
-
defer: Downloads in parallel, executes after HTML parsing completes, maintains execution order -
async: Downloads in parallel, executes immediately when ready, no guaranteed order
Use defer for scripts that depend on DOM or other scripts. Use async for independent scripts like analytics.
Incorrect: blocks rendering
export default function Document() {
return (
<html>
<head>
<script src="https://example.com/analytics.js" />
<script src="/scripts/utils.js" />
</head>
<body>{/* content */}</body>
</html>
)
}
Correct: non-blocking
import Script from 'next/script'
export default function Page() {
return (
<>
<Script src="https://example.com/analytics.js" strategy="afterInteractive" />
<Script src="/scripts/utils.js" strategy="beforeInteractive" />
</>
)
}
Note: In Next.js, prefer the next/script component with strategy prop instead of raw script tags:
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer
6.9 Use Explicit Conditional Rendering
Impact: LOW (prevents rendering 0 or NaN)
Use explicit ternary operators (? :) instead of && for conditional rendering when the condition can be 0, NaN, or other falsy values that render.
Incorrect: renders "0" when count is 0
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
Correct: renders nothing when count is 0
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
6.10 Use React DOM Resource Hints
Impact: HIGH (reduces load time for critical resources)
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
-
prefetchDNS(href): Resolve DNS for a domain you expect to connect to -
preconnect(href): Establish connection (DNS + TCP + TLS) to a server -
preload(href, options): Fetch a resource (stylesheet, font, script, image) you'll use soon -
preloadModule(href): Fetch an ES module you'll use soon -
preinit(href, options): Fetch and evaluate a stylesheet or script -
preinitModule(href): Fetch and evaluate an ES module
Example: preconnect to third-party APIs
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
Example: preload critical fonts and styles
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
// Preload font file
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
// Fetch and apply critical stylesheet immediately
preinit('/styles/critical.css', { as: 'style' })
return (
<html>
<body>{children}</body>
</html>
)
}
Example: preload modules for code-split routes
import { preloadModule, preinitModule } from 'react-dom'
function Navigation() {
const preloadDashboard = () => {
preloadModule('/dashboard.js', { as: 'script' })
}
return (
<nav>
<a href="/dashboard" onMouseEnter={preloadDashboard}>
Dashboard
</a>
</nav>
)
}
When to use each:
| API | Use case |
|-----|----------|
| prefetchDNS | Third-party domains you'll connect to later |
| preconnect | APIs or CDNs you'll fetch from immediately |
| preload | Critical resources needed for current page |
| preloadModule | JS modules for likely next navigation |
| preinit | Stylesheets/scripts that must execute early |
| preinitModule | ES modules that must execute early |
Reference: https://react.dev/reference/react-dom#resource-preloading-apis
6.11 Use useTransition Over Manual Loading States
Impact: LOW (reduces re-renders and improves code clarity)
Use useTransition instead of manual useState for loading states. This provides built-in isPending state and automatically manages transitions.
Incorrect: manual loading state
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isLoading, setIsLoading] = useState(false)
const handleSearch = async (value: string) => {
setIsLoading(true)
setQuery(value)
const data = await fetchResults(value)
setResults(data)
setIsLoading(false)
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isLoading && <Spinner />}
<ResultsList results={results} />
</>
)
}
Correct: useTransition with built-in pending state
import { useTransition, useState } from 'react'
function SearchResults() {
const [query, setQuery] = useState('')
const [results, setResults] = useState([])
const [isPending, startTransition] = useTransition()
const handleSearch = (value: string) => {
setQuery(value) // Update input immediately
startTransition(async () => {
// Fetch and update results
const data = await fetchResults(value)
setResults(data)
})
}
return (
<>
<input onChange={(e) => handleSearch(e.target.value)} />
{isPending && <Spinner />}
<ResultsList results={results} />
</>
)
}
Benefits:
-
Automatic pending state: No need to manually manage
setIsLoading(true/false) -
Error resilience: Pending state correctly resets even if the transition throws
-
Better responsiveness: Keeps the UI responsive during updates
-
Interrupt handling: New transitions automatically cancel pending ones
Reference: https://react.dev/reference/react/useTransition
7. JavaScript Performance
Impact: LOW-MEDIUM
Micro-optimizations for hot paths can add up to meaningful improvements.
7.1 Avoid Layout Thrashing
Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)
Avoid interleaving style writes with layout reads. When you read a layout property (like offsetWidth, getBoundingClientRect(), or getComputedStyle()) between style changes, the browser is forced to trigger a synchronous reflow.
This is OK: browser batches style changes
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
Incorrect: interleaved reads and writes force reflows
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
Correct: batch writes, then read once
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
Correct: batch reads, then writes
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
Better: use CSS classes
React example:
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See this gist and CSS Triggers for more information on layout-forcing operations.
7.2 Build Index Maps for Repeated Lookups
Impact: LOW-MEDIUM (1M ops to 2K ops)
Multiple .find() calls by the same key should use a Map.
Incorrect (O(n) per lookup):
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
Correct (O(1) per lookup):
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
7.3 Cache Property Access in Loops
Impact: LOW-MEDIUM (reduces lookups)
Cache object property lookups in hot paths.
Incorrect: 3 lookups × N iterations
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
Correct: 1 lookup total
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
7.4 Cache Repeated Function Calls
Impact: MEDIUM (avoid redundant computation)
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
Incorrect: redundant computation
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
Correct: cached results
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
Simpler pattern for single-value functions:
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast
7.5 Cache Storage API Calls
Impact: LOW-MEDIUM (reduces expensive I/O)
localStorage, sessionStorage, and document.cookie are synchronous and expensive. Cache reads in memory.
Incorrect: reads storage on every call
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
Correct: Map cache
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Cookie caching:
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
Important: invalidate on external changes
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
If storage can change externally (another tab, server-set cookies), invalidate cache:
7.6 Combine Multiple Array Iterations
Impact: LOW-MEDIUM (reduces iterations)
Multiple .filter() or .map() calls iterate the array multiple times. Combine into one loop.
Incorrect: 3 iterations
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
Correct: 1 iteration
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
7.7 Defer Non-Critical Work with requestIdleCallback
Impact: MEDIUM (keeps UI responsive during background tasks)
Use requestIdleCallback() to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
Incorrect: blocks main thread during user interaction
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
Correct: defers non-critical work to idle time
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
With timeout for required work:
// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
() => analytics.track('page_view', { path: location.pathname }),
{ timeout: 2000 }
)
Chunking large tasks:
function processLargeDataset(items: Item[]) {
let index = 0
function processChunk(deadline: IdleDeadline) {
// Process items while we have idle time (aim for <50ms chunks)
while (index < items.length && deadline.timeRemaining() > 0) {
processItem(items[index])
index++
}
// Schedule next chunk if more items remain
if (index < items.length) {
requestIdleCallback(processChunk)
}
}
requestIdleCallback(processChunk)
}
With fallback for unsupported browsers:
const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
scheduleIdleWork(() => {
// Non-critical work
})
When to use:
-
Analytics and telemetry
-
Saving state to localStorage/IndexedDB
-
Prefetching resources for likely next actions
-
Processing non-urgent data transformations
-
Lazy initialization of non-critical features
When NOT to use:
-
User-initiated actions that need immediate feedback
-
Rendering updates the user is waiting for
-
Time-sensitive operations
7.8 Early Length Check for Array Comparisons
Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
Incorrect: always runs expensive comparison
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
Two O(n log n) sorts run even when current.length is 5 and original.length is 100. There is also overhead of joining the arrays and comparing the strings.
Correct (O(1) length check first):
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
This new approach is more efficient because:
-
It avoids the overhead of sorting and joining the arrays when lengths differ
-
It avoids consuming memory for the joined strings (especially important for large arrays)
-
It avoids mutating the original arrays
-
It returns early when a difference is found
7.9 Early Return from Functions
Impact: LOW-MEDIUM (avoids unnecessary computation)
Return early when result is determined to skip unnecessary processing.
Incorrect: processes all items even after finding answer
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError