返回 AiToEarn
js-hoist-regexp.md
1 ---
2 title: Hoist RegExp Creation
3 impact: LOW-MEDIUM
4 impactDescription: avoids recreation
5 tags: javascript, regexp, optimization, memoization
6 ---
7
8 ## Hoist RegExp Creation
9
10 Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
11
12 **Incorrect (new RegExp every render):**
13
14 ```tsx
15 function 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
25 const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
26
27 function 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
39 Global regex (`/g`) has mutable `lastIndex` state:
40
41 ```typescript
42 const regex = /foo/g
43 regex.test('foo') // true, lastIndex = 3
44 regex.test('foo') // false, lastIndex = 0
45 ```
46
46 lines MARKDOWN