Back to JavaScript Performance

Hoist RegExp Creation

javascriptregexpoptimizationmemoization
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

Initializing regular expressions within render functions or loops forces the JavaScript engine to recompile the pattern repeatedly, consuming excessive memory and CPU cycles. This skill optimizes runtime performance by shifting regex instantiation out of hot code paths. By moving static patterns to the module-level scope or utilizing memoization hooks like useMemo, applications eliminate redundant object creation and garbage collection pressure. This is critical for high-frequency operations such as text highlighting, search filtering, or real-time form validation, where component re-renders would otherwise trigger thousands of unnecessary re-compilations. Proper scoping ensures that the regex engine interprets the pattern once, preserving state and minimizing execution latency. Implementing this practice is a fundamental step toward building responsive interfaces that remain fluid under load, preventing memory leaks and jitter in user interactions.

When to Use This Skill

  • Search result text highlighting components
  • Real-time form field input validation
  • Custom string parsing during render
  • Dynamic data filtering from list arrays

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Optimize my component's regex performance
  • Fix repeated regex instantiation in render
  • How to memoize regular expressions in React
  • Stop my regex from recomputing on every render
  • Move regex out of the render loop

What this skill does

  • Identifies regex instantiation within render lifecycles
  • Moves static expressions to the outer module scope
  • Wraps dynamic patterns in memoization hooks
  • Prevents constant recompilation of patterns during component updates
  • Mitigates side effects of stateful global flag usage

When not to use it

  • When the regex pattern is truly unique for every execution
  • When the pattern size is negligible and called once per session

Example workflow

  1. Audit the component for new RegExp() calls inside the render function
  2. Move static regex patterns to the top-level module scope for one-time initialization
  3. Identify dynamic regex patterns relying on component props or state
  4. Wrap dynamic RegExp generation in a useMemo hook with appropriate dependencies
  5. Verify that the regex global flag is handled carefully to prevent stale lastIndex state

Prerequisites

  • React or similar component-based framework
  • Understanding of JavaScript memory management

Pitfalls & limitations

  • !Global regex objects retain state via lastIndex which can cause unexpected false results on subsequent tests
  • !Incorrect dependency arrays in useMemo can lead to stale regex patterns
  • !Escaping user-provided input strings is required to prevent security vulnerabilities

FAQ

Why is creating a regex inside a component bad?
Every render creates a new object instance, triggering garbage collection and forcing the engine to re-parse the regex pattern, which is computationally expensive.
What happens if I use the /g flag in a hoisted regex?
Because the regex object is persistent, it keeps track of the 'lastIndex' property across calls, which can cause subsequent tests on the same string to fail unpredictably.
Is memoization always better than hoisting?
Hoisting is preferred for static patterns. Memoization is only necessary when the regex pattern depends on dynamic data like props or state.

How it compares

While manual optimization relies on identifying individual bottlenecks, this skill provides a structural pattern to systematically eliminate recompilation overhead, resulting in more predictable memory usage.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## 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

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/js-hoist-regexp/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/vercel-labs/agent-skills/js-hoist-regexp/SKILL.md
  • Cursor: ~/.cursor/skills/vercel-labs/agent-skills/js-hoist-regexp/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-hoist-regexp/SKILL.md

🚀 Install with CLI:
npx skills add vercel-labs/agent-skills

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid javascript performance issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under JavaScript Performance and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.