Skip to content

About

A zero-dependency React performance scanner that detects unnecessary re-renders, analyzes render chains, and provides actionable fix suggestions.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

ReactCheck

npm version License: MIT Node.js Version

A zero-dependency React performance scanner that detects unnecessary re-renders, analyzes render chains, and provides actionable fix suggestions.

Documentation | npm | GitHub

Features

  • Real-time Render Detection: Monitor React component renders in real-time via React DevTools hook
  • Render Chain Analysis: Trace cascade effects and identify root causes of performance issues
  • Fix Suggestions: Get actionable code suggestions (memo, useMemo, useCallback, context splitting)
  • Multiple Report Formats: Export reports as HTML, JSON, or Markdown
  • Framework Detection: Automatic detection and framework-specific tips for Next.js, Remix, Vite, CRA, Gatsby
  • Interactive TUI: Terminal-based UI for real-time monitoring
  • WebUI Dashboard: Real-time web dashboard with live updates at localhost:3199
  • Browser Overlay: Visual overlay showing component render statistics with severity colors
  • Zero Dependencies: Core functionality has no external dependencies

Installation

npm install --save-dev @oxog/react-check

Scanning a URL launches Chrome through Puppeteer, an optional peer dependency:

npm install --save-dev @oxog/react-check puppeteer
  • Node.js 18 or newer. The package ships ESM and CommonJS builds with TypeScript types.
  • React is not a dependency: ReactCheck observes the page through the React DevTools global hook, so it works with React 16.8+ development and production builds (verified with React 18). There is no static source analysis; nothing in your project is parsed.
  • When Puppeteer is missing, the CLI installs it once, only in an interactive terminal, into its own directory (~/.cache/react-check/puppeteer, %LOCALAPPDATA%\react-check\puppeteer on Windows, or $REACTCHECK_PUPPETEER_DIR) and loads it from there, so it also works with npx. If Puppeteer still cannot be loaded it exits with code 2 and explains what to install. In CI (CI set), without a TTY, or with REACTCHECK_NO_INSTALL=1 it does not install anything and exits with code 2.
  • The TypeScript declarations do not depend on Puppeteer: BrowserLauncher.getPage() returns a structural PuppeteerPageLike; pass Puppeteer's type for its full API: getPage<import('puppeteer').Page>().
  • Importing @oxog/react-check has no side effects and does not touch window, so it is safe in Node.js scripts, SSR bundles and test runners. The browser part ships separately as dist/browser-inject.global.js and is injected by the CLI.

Quick Start

CLI Usage

Scan a React application:

npx react-check scan http://localhost:3000

With options (durations are in seconds):

npx react-check scan http://localhost:3000 \
  --duration 60 \
  --output ./reports \
  --format html,json \
  --headless

With WebUI dashboard:

npx react-check scan http://localhost:3000 --webui

WebUI + custom port:

npx react-check scan http://localhost:3000 --webui --webui-port 8080

In CI:

npx react-check http://localhost:3000 --silent --headless --duration 30 --format json --output ./reactcheck-reports

Programmatic Usage

Scanner aggregates render events (RenderInfo) that you feed it, computes per-component statistics, severities, render chains and fix suggestions. The CLI and quickScan() feed it from the browser; you can also feed it yourself.

import { createScanner, generateHTMLReport } from '@oxog/react-check';

// Create a scanner instance
const scanner = createScanner({
  thresholds: { critical: 50, warning: 20 },
  include: ['MyComponent*'], // glob patterns: * and ?
  exclude: ['DebugPanel'],
});

// Listen for render events
scanner.on('render', (info) => {
  console.log(`${info.componentName} rendered in ${info.renderTime}ms`);
});

scanner.start();
scanner.addRender({
  componentName: 'MyComponentList',
  renderCount: 1,
  renderTime: 2.4,
  phase: 'update',
  necessary: false,
  timestamp: Date.now(),
});
scanner.stop();

console.log(scanner.getSnapshot()); // per-component stats, sorted by severity

Quick Scan API

Requires Puppeteer and Chrome. duration is in milliseconds here.

import { quickScan } from '@oxog/react-check';

const report = await quickScan('http://localhost:3000', {
  duration: 30000,
  headless: true,
  output: './reports',
  formats: ['html', 'json'],
});

console.log(`Found ${report.summary.criticalIssues} critical issues`);

quickScan throws a ReactCheckError with code BROWSER_LAUNCH_FAILED when Puppeteer or the page is unavailable and REACT_NOT_FOUND when no React render was observed.

CLI Commands

scan <url> (default command)

Scan a React application for performance issues. react-check <url> is the same as react-check scan <url>; without a URL in an interactive terminal a setup wizard starts.

react-check scan <url> [options]

General:
  -h, --help                     Show help message
  -v, --version                  Show version number
  --verbose                      Include detailed output
  -c, --config <path>            Config file path

Mode:
  -P, --proxy                    Start a proxy on <port + 1> that injects ReactCheck into any browser
  -s, --silent                   No TUI (for CI/CD)
  --headless                     Run browser in headless mode
  -W, --webui                    Enable WebUI dashboard
  --webui-port <port>            WebUI dashboard port (default: 3199)

Report:
  -r, --report                   Generate reports (implied by --format / --output)
  -f, --format <formats>         html, json, md, all or a comma-separated list (default: all)
  -o, --output <dir>             Report output directory (default: ./reactcheck-reports)
  --fix                          Show fix suggestions

Thresholds:
  --threshold-critical <n>       Render count for critical (default: 50)
  --threshold-warning <n>        Render count for warning (default: 20)
  --fps-threshold <n>            FPS drop threshold (default: 30)

Network:
  -p, --port <port>              WebSocket server port (default: 3099)
  -d, --duration <seconds>       Stop after this many seconds (otherwise Ctrl+C / q)

Unknown options and unknown commands are rejected (react-check watch <url> is an error, not a scan of http://watch; write http://<name> to scan a single-word host name). Options given on the command line override the config file, which overrides the defaults.

The terminal UI starts automatically in an interactive terminal (not with --silent, --proxy or --webui). There is no separate TUI-only or watch flag: without --duration a scan keeps running until you press q or Ctrl+C, and it always needs a browser (Puppeteer, or your own browser through --proxy).

Exit codes

Code Meaning
0 Scan finished without critical issues
1 Scan finished and found critical issues
2 Invalid usage, or the scan could not run (browser, port or page problems)

Proxy mode

react-check <url> --proxy starts a proxy on --port + 1 (default 3100). Open http://localhost:3100/<path> in any browser; the proxy injects ReactCheck into every HTML page. Alternatively add <script src="http://localhost:3100/__reactcheck__/scanner.js"></script> to your page before React loads.

report <input>

Generate reports from a JSON scan result.

react-check report scan-results.json --format html,md --output ./reports

detect [path]

Detect the React framework of a project (path to a directory or a package.json; --json prints machine-readable output).

react-check detect ./my-react-app

Demo

Run the included demo React app to test ReactCheck:

# Start demo app (runs on http://localhost:5173)
npm run demo

# In another terminal, scan with TUI
npm run demo:scan

# Or scan with WebUI dashboard
npm run demo:scan:webui

TUI Keyboard Shortcuts

While scanning with the interactive TUI, use these keyboard shortcuts:

Key Action
j / ↓ Move selection down
k / ↑ Move selection up
Enter View component details
Esc Go back to list view
f Show fix suggestions for selected component
c Show render chain view
o Toggle browser overlay on/off
r Generate report
p Pause/resume scanning
q Quit

Browser Overlay

ReactCheck injects a visual overlay into the target page that highlights component renders in real-time:

  • Flash Effect: Components flash with a colored background on each render
  • Border Highlight: Pulsing border shows render boundaries
  • Render Badges: Small badges show component name and render count
  • Severity Colors: Critical (red), Warning (orange), Healthy (green), using the scan's --threshold-warning / --threshold-critical values

Toggle Overlay

You can toggle the overlay on/off:

  1. TUI: Press o to toggle overlay visibility
  2. Browser Console: Run __REACTCHECK__.toggleOverlay()

The WebUI dashboard has no overlay toggle.

When overlay is disabled, render tracking continues but visual effects are hidden.

WebUI Dashboard

The WebUI dashboard provides a real-time web interface for monitoring React performance:

  • Live Summary: Components, renders, FPS, and issue counts update in real-time
  • Component List: Sortable and filterable table with severity indicators
  • Render Events: Live stream of render events as they occur
  • Render Chains: Visualization of cascade render chains
  • Auto-open: Dashboard opens automatically in your default browser

--webui replaces the terminal UI (the TUI does not run together with the dashboard); Chrome still opens the target page through Puppeteer.

# Scan with the WebUI dashboard instead of the TUI
react-check scan http://localhost:3000 --webui

# Custom WebUI port
react-check scan http://localhost:3000 --webui --webui-port 8080

Report Formats

HTML Report

Interactive HTML report with:

  • Summary dashboard
  • Component performance table with sorting
  • Render chain visualization
  • Fix suggestions with code examples

JSON Report

Machine-readable JSON format:

{
  "version": "1.0.0",
  "timestamp": "2025-01-15T10:30:00Z",
  "summary": {
    "totalComponents": 42,
    "totalRenders": 1250,
    "criticalIssues": 3,
    "warnings": 8,
    "healthy": 31
  },
  "components": [...],
  "chains": [...],
  "suggestions": [...]
}

Markdown Report

GitHub-friendly Markdown report suitable for issue tracking or documentation.

Configuration

ReactCheck looks for reactcheck.config.{js,mjs,cjs,json}, .reactcheckrc, .reactcheckrc.js or .reactcheckrc.json in the current directory and its parents (react-check init creates one).

/** @type {import('@oxog/react-check').ReactCheckConfig} */
export default {
  // Component name patterns (* and ?)
  include: [],
  exclude: ['DebugPanel'],
  thresholds: {
    critical: 50, // render count for critical severity
    warning: 20,  // render count for warning severity
    fps: 30,      // FPS drop threshold
  },
  report: {
    formats: ['html', 'json'],
    output: './reactcheck-reports',
  },
  // Fix-suggestion rules: 'off' disables a rule
  rules: {
    'state-too-high': 'off',
  },
};

Rule ids: unnecessary-rerenders-memo, expensive-computation-memo, function-prop-stability, context-over-subscription, state-too-high, extract-heavy-child.

Fix Categories

ReactCheck provides fix suggestions in these categories:

  • React.memo: Wrap components that receive stable props
  • useMemo: Memoize expensive computed values
  • useCallback: Memoize callback functions passed to children
  • Context Splitting: Split large contexts to reduce re-render scope
  • State Colocation: Move state closer to where it's used

API Reference

Core Classes

Scanner

Main scanning engine.

const scanner = new Scanner(config);
scanner.on('render', handler);
scanner.on('chain', handler);
scanner.on('fps-drop', handler);
scanner.start();
scanner.addRender(renderInfo, parentName); // the CLI forwards browser renders here
scanner.stop();
const components = scanner.getSnapshot();
const summary = scanner.getSummary();
const suggestions = scanner.getSuggestions(); // regenerated from the current stats
const data = scanner.export(); // { stats, suggestions, config }

There is no getReport(): quickScan() returns a full SessionReport, or build one from export() for the report generators.

ChainAnalyzer

Analyzes render chains and cascade effects.

const analyzer = new ChainAnalyzer({ windowSize: 16 });
analyzer.on('chain', (chain) => console.log(chain.trigger, chain.chain.join(' -> ')));
analyzer.addRender(renderInfo, parentName);
const path = analyzer.getComponentChain('Leaf'); // e.g. ['App', 'Ticker', 'Leaf']

Chains need parent relationships. Renders recorded by the injected browser script carry render.parent, which Scanner.addRender() uses when no parent argument is given.

FixSuggester

Generates fix suggestions based on component statistics.

const suggester = new FixSuggester();
const suggestions = suggester.analyze(componentStats);

Utility Functions

// Report generation
generateHTMLReport(report);
generateJSONReport(report);
generateMarkdownReport(report);

// Framework detection
detectFramework(packageJsonPath?);
detectFrameworkFromWindow(); // browser only
getFrameworkTips(framework, issues);

// Formatting utilities
formatDuration(ms);
formatBytes(bytes);
formatPercent(value);
formatRenderTime(ms);

Browser Integration

Manual Injection

import { installReactCheck } from '@oxog/react-check';

// Must run before React loads; connects to a CLI started with --proxy or a scan
const injector = installReactCheck(window);

// Later: restores the React DevTools hook, removes the overlay, stops reconnecting
injector?.destroy();

Or use the scanner directly:

import { BrowserScanner } from '@oxog/react-check';

const scanner = new BrowserScanner({ exclude: ['DevTools*'] }, window);
scanner.on('render', ({ render, element }) => {
  console.log(render.componentName, render.necessary ? '' : '(unnecessary)', element);
});
scanner.start(); // hooks into React; stop() unhooks

Only components that actually rendered in a commit are reported; React.memo bail-outs and untouched subtrees are not counted.

Proxy Server

import { ProxyServer, WebSocketServer } from '@oxog/react-check';

const wsServer = new WebSocketServer(3099);
const proxy = new ProxyServer({
  target: 'http://localhost:3000',
  port: 8080,
  wsPort: 3099,
});

await wsServer.start();
await proxy.start(); // serves the bundled browser script at /__reactcheck__/scanner.js

// Open http://localhost:8080 in browser

Framework Support

ReactCheck automatically detects and provides tailored tips for:

Framework Features Detected
Next.js App Router, Pages Router, RSC
Remix Routes, loaders
Vite HMR, React plugin
Create React App react-scripts
Gatsby gatsby-* packages

Architecture

src/
├── core/           # Core scanning engine
│   ├── scanner.ts  # Main scanner
│   ├── chain.ts    # Render chain analyzer
│   ├── fix.ts      # Fix suggester
│   ├── stats.ts    # Statistics collector
│   └── fiber.ts    # React fiber utilities
├── browser/        # Browser-side modules
│   ├── injector.ts # Page injector (side-effect free)
│   ├── inject.ts   # IIFE entry -> dist/browser-inject.global.js
│   ├── scanner.ts  # Browser scanner
│   └── overlay.ts  # Visual overlay
├── server/         # Node.js server modules
│   ├── websocket.ts # WebSocket server
│   ├── proxy.ts     # HTTP proxy
│   └── browser.ts   # Puppeteer wrapper
├── report/         # Report generators
│   ├── html.ts     # HTML report
│   ├── json.ts     # JSON report
│   └── markdown.ts # Markdown report
├── detect/         # Framework detection
│   └── framework.ts
├── cli/            # CLI implementation
│   ├── index.ts    # CLI entry
│   └── tui/        # Terminal UI
├── webui/          # Web dashboard
│   ├── server.ts   # HTTP + WebSocket server
│   └── dashboard.ts # Dashboard HTML generator
└── utils/          # Shared utilities
    ├── colors.ts   # ANSI colors
    ├── format.ts   # Formatters
    ├── fs.ts       # File system
    └── logger.ts   # Logging

License

MIT

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting a PR.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: npm test
  5. Run build: npm run build
  6. Submit a pull request

About

A zero-dependency React performance scanner that detects unnecessary re-renders, analyzes render chains, and provides actionable fix suggestions.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages