AGENTS.md · 96000
= true errorMessage = 'Name required' } // Continues checking all users even after error found }
return hasError ? { valid: false, error: errorMessage } : { valid: true } }
**Correct: returns immediately on first error**
```typescript
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 }
}
7.10 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) => ...)}</>
}
Warning: global regex has mutable state
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
Global regex (/g) has mutable lastIndex state:
7.11 Use flatMap to Map and Filter in One Pass
Impact: LOW-MEDIUM (eliminates intermediate array)
Chaining .map().filter(Boolean) creates an intermediate array and iterates twice. Use .flatMap() to transform and filter in a single pass.
Incorrect: 2 iterations, intermediate array
const userNames = users
.map(user => user.isActive ? user.name : null)
.filter(Boolean)
Correct: 1 iteration, no intermediate array
const userNames = users.flatMap(user =>
user.isActive ? [user.name] : []
)
More examples:
// Extract valid emails from responses
// Before
const emails = responses
.map(r => r.success ? r.data.email : null)
.filter(Boolean)
// After
const emails = responses.flatMap(r =>
r.success ? [r.data.email] : []
)
// Parse and filter valid numbers
// Before
const numbers = strings
.map(s => parseInt(s, 10))
.filter(n => !isNaN(n))
// After
const numbers = strings.flatMap(s => {
const n = parseInt(s, 10)
return isNaN(n) ? [] : [n]
})
When to use:
-
Transforming items while filtering some out
-
Conditional mapping where some inputs produce no output
-
Parsing/validating where invalid inputs should be skipped
7.12 Use Loop for Min/Max Instead of Sort
Impact: LOW (O(n) instead of O(n log n))
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
Incorrect (O(n log n) - sort to find latest):
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
Sorts the entire array just to find the maximum value.
Incorrect (O(n log n) - sort for oldest and newest):
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
Still sorts unnecessarily when only min/max are needed.
Correct (O(n) - single loop):
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
Single pass through the array, no copying, no sorting.
Alternative: Math.min/Math.max for small arrays
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see the fiddle. Use the loop approach for reliability.
7.13 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))
7.14 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>
}
Why this matters in React:
-
Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
-
Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
Browser support: fallback for older browsers
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
.toSorted() is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
Other immutable array methods:
-
.toSorted()- immutable sort -
.toReversed()- immutable reverse -
.toSpliced()- immutable splice -
.with()- immutable element replacement
8. Advanced Patterns
Impact: LOW
Advanced patterns for specific cases that require careful implementation.
8.1 Do Not Put Effect Events in Dependency Arrays
Impact: LOW (avoids unnecessary effect re-runs and lint errors)
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by useEffectEvent in a useEffect dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
Incorrect: Effect Event added as a dependency
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId, handleConnected])
}
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
Correct: depend on reactive values, not the Effect Event
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
}
Reference: https://react.dev/reference/react/useEffectEvent#effect-event-in-deps
8.2 Initialize App Once, Not Per Mount
Impact: LOW-MEDIUM (avoids duplicate init in development)
Do not put app-wide initialization that must run once per app load inside useEffect([]) of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
Incorrect: runs twice in dev, re-runs on remount
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
Correct: once per app load
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
Reference: https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application
8.3 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: (e) => 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: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
Alternative: use useEffectEvent if you're on latest React:
useEffectEvent provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
8.4 useEffectEvent 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.
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: using React's useEffectEvent
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}