react-doctor/js-hoist-regexp
Hoist `new RegExp(...)` (or large regex literals) to a module-level constant so it isn't recompiled on every loop iteration
- Category: Performance
- Severity: warn
- Source:
oxlint-plugin-react-doctor - Framework: global
- Enabled when: always
Validation prompt
Use this to decide whether a fired diagnostic is real or a false positive.
The rule fires on new RegExp(...) (identifier callee) anywhere inside a loop body (for / for...in / for...of / while / do-while). Regex literals like /foo/g are NOT flagged. False positive only if the pattern is built from a value that changes per iteration — in that case cache via a Map<pattern, RegExp> instead.
Fix prompt
Use this once validation confirms the diagnostic is real.
Move to a module-level const FOO_REGEX = /pattern/flags; (the literal form is compiled once at parse time and is fastest) or const FOO_REGEX = new RegExp(pattern); declared above the loop. RegExp construction parses the pattern and compiles a state machine — avoid paying that cost N times. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Related rules
More Performance rules from the rules reference:
react-doctor/js-index-maps: Build an index `Map` once outside the loop instead of `array.find(...)` inside itreact-doctor/js-length-check-first: Short-circuit with `a.length === b.length && a.every((x, i) => x === b[i])` — unequal-length arrays exit immediatelyreact-doctor/js-min-max-loop: Use `Math.min(...array)` / `Math.max(...array)` instead of sorting just to read the first or last elementreact-doctor/js-set-map-lookups: Use a `Set` or `Map` for repeated membership tests / keyed lookups — `Array.includes`/`find` is O(n) per callreact-doctor/js-tosorted-immutable: Use `array.toSorted()` (ES2023) instead of `[...array].sort()` for immutable sorting without the spread allocation