| 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 |
| 16 | const regex = |
| 17 | const parts = |
| 18 | return <>{parts. |
| 19 | } |
| 20 | ``` |
| 21 | |
| 22 | **Correct (memoize or hoist):** |
| 23 | |
| 24 | ```tsx |
| 25 | const EMAIL_REGEX = / |
| 26 | |
| 27 | function Highlighter({ text |
| 28 | const regex = |
| 29 | () => new |
| 30 | [query] |
| 31 | ) |
| 32 | const parts = |
| 33 | return <>{parts. |
| 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 = / |
| 43 | regex.test("foo" |
| 44 | regex.test("foo" |
| 45 | ``` |