Instruction file imported from DataCovey/nornweave (
.cursor/rules/react.mdc). Copyright stays with the author.
React Best Practices
Comprehensive performance optimization guide for React applications. Contains 35+ rules across 7 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations.
1. Eliminating Waterfalls
Impact: CRITICAL
Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
1.1 Defer Await Until Needed
Impact: HIGH (avoids blocking unused code paths)
Move await operations into the branches where they're actually used to avoid blocking code paths that don't need them.
Incorrect: blocks both branches
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}
Correct: only blocks when needed
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}
Another example: early return optimization
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
1.2 Promise.all() for Independent Operations
Impact: CRITICAL (2-10× improvement)
When async operations have no interdependencies, execute them concurrently using Promise.all().
Incorrect: sequential execution, 3 round trips
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
Correct: parallel execution, 1 round trip
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
1.3 Dependency-Based Parallelization
Impact: CRITICAL (2-10× improvement)
For operations with partial dependencies, start independent operations immediately, even if you don't await them yet.
Incorrect: config waits for auth, data waits for both
async function fetchData() {
const session = await auth()
const config = await fetchConfig()
const data = await fetchUserData(session.user.id)
return { data, config }
}
Correct: auth and config start immediately
async function fetchData() {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchUserData(session.user.id)
])
return { data, config }
}
1.4 Strategic Suspense Boundaries
Impact: HIGH (faster initial paint)
Use Suspense boundaries to show the wrapper UI faster while data loads.
Incorrect: wrapper blocked by data fetching
function Page() {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchData().then(d => {
setData(d)
setLoading(false)
})
}, [])
if (loading) return <Skeleton />
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
The entire layout waits for data even though only the middle section needs it.
Correct: wrapper shows immediately, data streams in
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
function DataDisplay() {
const data = use(fetchData()) // Using React's use() hook
return <div>{data.content}</div>
}
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
When NOT to use this pattern:
- Critical data needed for layout decisions (affects positioning)
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
2. Bundle Size Optimization
Impact: CRITICAL
Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
2.1 Avoid Barrel File Imports
Impact: CRITICAL (200-800ms import cost, slow builds)
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. Barrel files are entry points that re-export multiple modules (e.g., index.js that does export * from './module').
Popular icon and component libraries can have up to 10,000 re-exports in their entry file. For many React packages, it takes 200-800ms just to import them.
Incorrect: imports entire library
import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev
Correct: imports only what you need
import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'
// Loads only 3 modules (~2KB vs ~1MB)
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: lucide-react, @mui/material, @mui/icons-material, @tabler/icons-react, react-icons, @headlessui/react, @radix-ui/react-*, lodash, ramda, date-fns, rxjs, react-use.
2.2 Conditional Module Loading
Impact: HIGH (loads large data only when needed)
Load large data or modules only when a feature is activated.
Example: lazy-load animation frames
function AnimationPlayer({ enabled }: { enabled: boolean }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames) {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
2.3 Defer Non-Critical Third-Party Libraries
Impact: MEDIUM (loads after initial render)
Analytics, logging, and error tracking don't block user interaction. Load them lazily.
Incorrect: blocks initial bundle
import { Analytics } from '@analytics/react'
export default function App({ children }) {
return (
<div>
{children}
<Analytics />
</div>
)
}
Correct: loads lazily
import { lazy, Suspense } from 'react'
const Analytics = lazy(() => import('@analytics/react').then(m => ({ default: m.Analytics })))
export default function App({ children }) {
return (
<div>
{children}
<Suspense fallback={null}>
<Analytics />
</Suspense>
</div>
)
}
2.4 Dynamic Imports for Heavy Components
Impact: CRITICAL (directly affects TTI and LCP)
Use React.lazy() to lazy-load large components not needed on initial render.
Incorrect: Monaco bundles with main chunk ~300KB
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
Correct: Monaco loads on demand
import { lazy, Suspense } from 'react'
const MonacoEditor = lazy(() => import('./monaco-editor').then(m => ({ default: m.MonacoEditor })))
function CodePanel({ code }: { code: string }) {
return (
<Suspense fallback={<div>Loading editor...</div>}>
<MonacoEditor value={code} />
</Suspense>
)
}
2.5 Preload Based on User Intent
Impact: MEDIUM (reduces perceived latency)
Preload heavy bundles before they're needed to reduce perceived latency.
Example: preload on hover/focus
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
void import('./monaco-editor')
}
return (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
Example: preload when feature flag is enabled
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled) {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
3. Client-Side Data Fetching
Impact: MEDIUM-HIGH
Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
3.1 Deduplicate Global Event Listeners
Impact: LOW (single listener for N components)
Use useSWRSubscription() or similar patterns to share global event listeners across component instances.
Incorrect: N instances = N listeners
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
When using the useKeyboardShortcut hook multiple times, each instance will register a new listener.
Correct: N instances = 1 listener
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
3.2 Use SWR or React Query for Automatic Deduplication
Impact: MEDIUM-HIGH (automatic deduplication)
SWR/React Query enable request deduplication, caching, and revalidation across component instances.
Incorrect: no deduplication, each instance fetches
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
Correct: multiple instances share one request
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
For immutable data:
import useSWRImmutable from 'swr/immutable'
function StaticContent() {
const { data } = useSWRImmutable('/api/config', fetcher)
}
For mutations:
import useSWRMutation from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
4. Re-render Optimization
Impact: MEDIUM
Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
4.1 Defer State Reads to Usage Point
Impact: MEDIUM (avoids unnecessary subscriptions)
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
Incorrect: subscribes to all searchParams changes
function ShareButton({ chatId }: { chatId: string }) {
const [searchParams] = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
Correct: reads on demand, no subscription
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
4.2 Extract to Memoized Components
Impact: MEDIUM (enables early returns)
Extract expensive work into memoized components to enable early returns before computation.
Incorrect: computes avatar even when loading
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
Correct: skips computation when loading
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
Note: If your project has React Compiler enabled, manual memoization with memo() and useMemo() is not necessary. The compiler automatically optimizes re-renders.
4.3 Narrow Effect Dependencies
Impact: LOW (minimizes effect re-runs)
Specify primitive dependencies instead of objects to minimize effect re-runs.
Incorrect: re-runs on any user field change
useEffect(() => {
console.log(user.id)
}, [user])
Correct: re-runs only when id changes
useEffect(() => {
console.log(user.id)
}, [user.id])
For derived state, compute outside effect:
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])
4.4 Subscribe to Derived State
Impact: MEDIUM (reduces re-render frequency)
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
Incorrect: re-renders on every pixel change
function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'}>
}
Correct: re-renders only when boolean changes
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'}>
}
4.5 Use Functional setState Updates
Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable.
Incorrect: requires state as dependency
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
Correct: stable callbacks, no stale closures
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
When to use functional updates:
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
When direct updates are fine:
- Setting state to a static value:
setCount(0) - Setting state from props/arguments only:
setName(newName) - State doesn't depend on previous value
4.6 Use Lazy State Initialization
Impact: MEDIUM (wasted computation on every render)
Pass a function to useState for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
Incorrect: runs on every render
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
Correct: runs only once
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
4.7 Use Transitions for Non-Urgent Updates
Impact: MEDIUM (maintains UI responsiveness)
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
Incorrect: blocks UI on every scroll
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
Correct: non-blocking updates
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
5. Rendering Performance
Impact: MEDIUM
Optimizing the rendering process reduces the work the browser needs to do.
5.1 Animate SVG Wrapper Instead of SVG Element
Impact: LOW (enables hardware acceleration)
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a <div> and animate the wrapper instead.
Incorrect: animating SVG directly - no hardware acceleration
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
Correct: animating wrapper div - hardware accelerated
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
5.2 CSS content-visibility for Long Lists
Impact: HIGH (faster initial render)
Apply content-visibility: auto to defer off-screen rendering.
CSS:
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
Example:
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
5.3 Hoist Static JSX Elements
Impact: LOW (avoids re-creation)
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.
5.4 Optimize SVG Precision
Impact: LOW (reduces file size)
Reduce SVG coordinate precision to decrease file size.
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
5.5 Use Activity Component for Show/Hide
Impact: MEDIUM (preserves state/DOM)
Use React's <Activity> (React 19+) 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.
5.6 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. JavaScript Performance
Impact: LOW-MEDIUM
Micro-optimizations for hot paths can add up to meaningful improvements.
6.1 Batch DOM CSS Changes
Impact: MEDIUM (reduces reflows/repaints)
Avoid changing styles one property at a time. Group multiple CSS changes together via classes or cssText to minimize browser reflows.
Incorrect: multiple reflows
function updateElementStyles(element: HTMLElement) {
// Each line triggers a reflow
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
Correct: add class - single reflow
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
}
React example:
// Incorrect: changing styles one by one
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
ref.current.style.height = '200px'
ref.current.style.backgroundColor = 'blue'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
6.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)
}))
}
6.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)
}
6.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.
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>
)
}
6.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
}
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()
}
})
6.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)
}
6.7 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 = true
errorMessage = 'Name required'
}
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
Correct: returns immediately on first error
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
6.8 Hoist RegExp Creation
Impact: LOW-MEDIUM (avoids recreation)
Don't create RegExp inside render. Hoist to module scope or memoize with useMemo().
Incorrect: new RegExp every render
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
Correct: memoize or hoist
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
6.9 Use Set/Map for O(1) Lookups
Impact: LOW-MEDIUM (O(n) to O(1))
Convert arrays to Set/Map for repeated membership checks.
Incorrect (O(n) per check):
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
Correct (O(1) per check):
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
6.10 Use toSorted() Instead of sort() for Immutability
Impact: MEDIUM-HIGH (prevents mutation bugs in React state)
.sort() mutates the array in place, which can cause bugs with React state and props. Use .toSorted() to create a new sorted array without mutation.
Incorrect: mutates original array
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
Correct: creates new array
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
Browser support: fallback for older browsers
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
Other immutable array methods:
.toSorted()- immutable sort.toReversed()- immutable reverse.toSpliced()- immutable splice.with()- immutable element replacement
7. Advanced Patterns
Impact: LOW
Advanced patterns for specific cases that require careful implementation.
7.1 Store Event Handlers in Refs
Impact: LOW (stable subscriptions)
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
Incorrect: re-subscribes on every render
function useWindowEvent(event: string, handler: () => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
Correct: stable subscription
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: () => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
7.2 useLatest for Stable Callback Refs
Impact: LOW (prevents effect re-runs)
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
Implementation:
function useLatest<T>(value: T) {
const ref = useRef(value)
useEffect(() => {
ref.current = value
}, [value])
return ref
}
Incorrect: effect re-runs on every callback change
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
Correct: stable effect, fresh callback
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchRef = useLatest(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchRef.current(query), 300)
return () => clearTimeout(timeout)
}, [query])
}