mcpField
J
js-hoist-regexp

js-hoist-regexp

github.com/theorcdevDevelopment2.1k36 installsUpdated 2d ago
Repository

About js-hoist-regexp

A JavaScript and React rendering skill that recommends creating regular expressions outside render or memoizing them. It also explains the mutable state of global regexes.

Key features

  1. 01Hoist RegExp creation out of render
  2. 02Memoize query-dependent expressions
  3. 03Account for global regex lastIndex state

Use cases

  1. 01Avoid recreating regexes on each render
  2. 02Prevent unexpected behavior when testing global regexes

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/theorcdev/8bitcn-ui --skill js-hoist-regexp

After installing, type/js-hoist-regexpin Claude Code to confirm it loaded.

Details

From the project README

Hoist RegExp Creation

Don't create RegExp inside render. Hoist to module scope or memoize with useMemo().

Incorrect (new RegExp every render):

function Highlighter({ text, query }: Props) {
  const regex = new RegExp(`(${query})`, 'gi')
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

Correct (memoize or hoist):

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function Highlighter({ text, query }: Props) {
  const regex = useMemo(
    () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
    [query]
  )
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

Warning (global regex has mutable state):

Global regex (/g) has mutable lastIndex state:

const regex = /foo/g
regex.test('foo')  // true, lastIndex = 3
regex.test('foo')  // false, lastIndex = 0

Comments

Markdown supported