556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / js-hoist-regexp.md
1.0 KB
1--- 2title: Hoist RegExp Creation 3impact: LOW-MEDIUM 4impactDescription: avoids recreation 5tags: javascript, regexp, optimization, memoization 6--- 7 8## Hoist RegExp Creation 9 10Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`. 11 12**Incorrect (new RegExp every render):** 13 14```tsx 15function Highlighter({ text, query }: Props) { 16 const regex = new RegExp(`(${query})`, 'gi') 17 const parts = text.split(regex) 18 return <>{parts.map((part, i) => ...)}</> 19} 20``` 21 22**Correct (memoize or hoist):** 23 24```tsx 25const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ 26 27function Highlighter({ text, query }: Props) { 28 const regex = useMemo( 29 () => new RegExp(`(${escapeRegex(query)})`, 'gi'), 30 [query] 31 ) 32 const parts = text.split(regex) 33 return <>{parts.map((part, i) => ...)}</> 34} 35``` 36 37**Warning (global regex has mutable state):** 38 39Global regex (`/g`) has mutable `lastIndex` state: 40 41```typescript 42const regex = /foo/g 43regex.test('foo') // true, lastIndex = 3 44regex.test('foo') // false, lastIndex = 0 45```