Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/js-hoist-regexp.md
1---2title: Hoist RegExp Creation3impact: LOW-MEDIUM4impactDescription: avoids recreation5tags: javascript, regexp, optimization, memoization6---78## Hoist RegExp Creation910Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.1112**Incorrect (new RegExp every render):**1314```tsx15function Highlighter({ text, query }: Props) {16const regex = new RegExp(`(${query})`, 'gi')17const parts = text.split(regex)18return <>{parts.map((part, i) => ...)}</>19}20```2122**Correct (memoize or hoist):**2324```tsx25const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/2627function Highlighter({ text, query }: Props) {28const regex = useMemo(29() => new RegExp(`(${escapeRegex(query)})`, 'gi'),30[query]31)32const parts = text.split(regex)33return <>{parts.map((part, i) => ...)}</>34}35```3637**Warning (global regex has mutable state):**3839Global regex (`/g`) has mutable `lastIndex` state:4041```typescript42const regex = /foo/g43regex.test('foo') // true, lastIndex = 344regex.test('foo') // false, lastIndex = 045```46