react-scan README

The project's README from github.com/aidenybai/react-scan. As one markdown file: README.md.

React Scan

You can still use React Scan, but we recommend React Doctor

React Doctor brings React Scan’s performance focus to coding agents, with static checks for architecture, security, accessibility, and more. Try React Doctor →

React Scan automatically detects performance issues in your React app.

Quick Start

npx -y react-scan@latest init

Try out a demo! →

React Scan in action

Install

The init command will automatically detect your framework, install react-scan via npm, and set up your project.

npx -y react-scan@latest init

Manual Installation

Install the package:

npm install -D react-scan

Then add the script tag to your app. Pick the guide for your framework:

Script Tag

Paste this before any scripts in your index.html:

<!-- paste this BEFORE any scripts -->
<script
  crossOrigin="anonymous"
  src="//unpkg.com/react-scan/dist/auto.global.js"
></script>

Next.js (App Router)

Add this inside of your app/layout.tsx:

import Script from "next/script";

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <Script
          src="//unpkg.com/react-scan/dist/auto.global.js"
          crossOrigin="anonymous"
          strategy="beforeInteractive"
        />
      </head>
      <body>{children}</body>
    </html>
  );
}

Next.js (Pages Router)

Add this into your pages/_document.tsx:

import { Html, Head, Main, NextScript } from "next/document";
import Script from "next/script";

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <Script
          src="//unpkg.com/react-scan/dist/auto.global.js"
          crossOrigin="anonymous"
          strategy="beforeInteractive"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Vite

Example index.html with React Scan enabled:

<!doctype html>
<html lang="en">
  <head>
    <script
      crossOrigin="anonymous"
      src="//unpkg.com/react-scan/dist/auto.global.js"
    ></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Remix

Add this inside your app/root.tsx:

import { Links, Meta, Outlet, Scripts } from "@remix-run/react";

export default function App() {
  return (
    <html>
      <head>
        <Meta />
        <script
          crossOrigin="anonymous"
          src="//unpkg.com/react-scan/dist/auto.global.js"
        />
        <Links />
      </head>
      <body>
        <Outlet />
        <Scripts />
      </body>
    </html>
  );
}

Browser Extension

Install the extension by following the guide here.

API Reference

Options
export interface Options {
  /**
   * Enable/disable scanning
   * @default true
   */
  enabled?: boolean;

  /**
   * Force React Scan to run in production (not recommended)
   * @default false
   */
  dangerouslyForceRunInProduction?: boolean;

  /**
   * Log renders to the console
   * @default false
   */
  log?: boolean;

  /**
   * Show toolbar bar
   * @default true
   */
  showToolbar?: boolean;

  /**
   * Animation speed
   * @default "fast"
   */
  animationSpeed?: "slow" | "fast" | "off";

  onCommitStart?: () => void;
  onRender?: (fiber: Fiber, renders: Array<Render>) => void;
  onCommitFinish?: () => void;
}

Why React Scan?

React can be tricky to optimize.

The issue is that component props are compared by reference, not value. This is intentional -- rendering can be cheap to run.

However, this makes it easy to accidentally cause unnecessary renders, making the app slow. Even production apps with hundreds of engineers can't fully optimize their apps (see GitHub, Twitter, and Instagram).

<ExpensiveComponent onClick={() => alert("hi")} style={{ color: "purple" }} />

React Scan helps you identify these issues by automatically detecting and highlighting renders that cause performance issues.

Resources & Contributing

Want to try it out? Check the demo.

Looking to contribute? Check the Contributing Guide.

Want to talk to the community? Join our Discord.

Find a bug? Head to our issue tracker.

→ Start contributing on GitHub

Acknowledgments

License

React Scan is MIT-licensed open-source software by Aiden Bai, Million Software, Inc., and contributors.

react-scan (aidenybai/react-scan)

Searching Database…

Что это такое?React Scan — это инструмент для разработчиков, который автоматически находит проблемы с производительностью в React-приложении: он подсвечивает именно те компоненты, которые нужно оптимизировать, не требует изменений в коде и всегда доступен через панель инструментов на странице.
Это что-то, что я устанавливаю в свой проект, или отдельное приложение?И то и другое: это npm-пакет, который подключается к приложению через тег script, а также отдельное расширение для браузера, если не хочется трогать свой код.
Как быстрее всего добавить его в своё приложение?Запустите в проекте команду init: она сама определит фреймворк, установит react-scan через npm и всё настроит. Ручной путь — установить пакет и самостоятельно добавить его тег script.
Работает ли он с фреймворками вроде Next.js?Да — есть готовые руководства с кодом для копирования для Next.js (App Router) и Remix, а для любого index.html подойдёт простой тег script; команда init к тому же сама определяет ваш фреймворк.
Стоит ли им пользоваться, или его уже что-то заменило?Он по-прежнему работает и остаётся open source, но в README авторы теперь отправляют пользователей к React Doctor — он переносит фокус на производительность в агентов для программирования и добавляет статические проверки архитектуры, безопасности и доступности.
Можно ли бесплатно использовать его в своих проектах?Да — React Scan это open-source-проект под лицензией MIT от Aiden Bai, Million Software, Inc. и контрибьюторов.
Из-за чего React-приложения на самом деле тормозят, по его мнению?Пропсы компонентов сравниваются по ссылке, а не по значению, поэтому легко вызвать лишние рендеры — именно их React Scan и подсвечивает. Даже в продакшене приложений с сотнями инженеров (упоминаются GitHub, Twitter, Instagram) их не удаётся полностью оптимизировать.
Могу ли я отслеживать рендеры из своего кода?Да — в API есть функция scan() и хук useScan() для запуска сканирования, setOptions()/getOptions() для управления на лету, а также onRender(), чтобы вызывать колбэк при рендерах конкретного компонента.
Что его вдохновило?React Devtools — за исходную идею подсветки рендеров, Million Lint — за подходы к сканированию и линтингу, а Why Did You Render? — за идею обнаружения лишних рендеров.
Можно ли попробовать его без установки чего-либо?Да — в README есть ссылка на онлайн-демо, где можно увидеть подсветку рендеров в действии ещё до добавления в своё приложение.
Creator
aidenybai
Size
43.9 MB
Stars
21.9K
Age
2y
Commits · 90 Days