npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ddll/react-performance-monitor

v1.0.0-beta3

Published

React 性能监控工具包 - 监控组件渲染、内存泄漏、DOM 变更等性能问题

Readme

React 性能监控工具包

一个可在任何 React 项目中使用的性能监控解决方案,帮助在开发环境快速发现性能问题。

特性

  • 零外部依赖:核心功能仅依赖 React,无其他依赖
  • 轻量级:体积小,不影响生产环境性能
  • 易于集成:提供 Hook 和 HOC 两种使用方式
  • 功能完整:监控渲染、内存、DOM 变更
  • 可配置:支持自定义阈值和回调
  • TypeScript 友好:完整的 JSDoc 注释

安装

npm / yarn / pnpm

npm install @ddll/react-performance-monitor
# 或
yarn add @ddll/react-performance-monitor
# 或
pnpm add @ddll/react-performance-monitor

本地开发(link 方式)

pnpm --dir "项目路径" add "@ddll/react-performance-monitor@link:知识库/packages/react-performance-monitor"

手动复制

react-performance-monitor 目录复制到你的项目中。

快速开始

方式一:使用 Provider 组件(推荐,最简单)

最简单的使用方式,只需包裹你的应用:

import { PerformanceMonitorProvider } from '@ddll/react-performance-monitor'

function App() {
  return (
    <PerformanceMonitorProvider
      enabled={process.env.NODE_ENV === 'development'}
      showControlPanel={true}
      warnThreshold={{ renderCount: 50, renderTime: 16 }}
    >
      <YourApp />
    </PerformanceMonitorProvider>
  )
}

特性

  • ✅ 自动启用(开发环境默认启用)
  • ✅ 自动启动监控
  • ✅ 可选的控制面板(纯 HTML/CSS,无依赖)
  • ✅ 零配置即可使用

方式二:使用 Logger 组件(带日志面板)

使用 Hook 方式,提供日志显示面板:

import { PerformanceMonitorLogger } from '@ddll/react-performance-monitor'

function App() {
  return (
    <>
      <YourApp />
      <PerformanceMonitorLogger
        enabled={process.env.NODE_ENV === 'development'}
        autoStart={true}
        showPanel={true}
        position="bottom-right"
      />
    </>
  )
}

特性

  • ✅ 使用 Hook 方式,不包裹子组件
  • ✅ 内置日志收集和显示
  • ✅ 实时显示性能警告
  • ✅ 可展开/收起的日志面板
  • ✅ 多个标签页:日志、渲染统计、内存、DOM

方式三:使用 Hook(灵活控制)

需要更灵活的控制时使用:

import { useReactPerformanceMonitor } from '@ddll/react-performance-monitor'

function App() {
  const { ComponentProfiler, monitorActive, startMonitor, stopMonitor } = useReactPerformanceMonitor()

  return (
    <div>
      <button onClick={startMonitor}>开始监控</button>
      <button onClick={stopMonitor}>停止监控</button>
      
      <ComponentProfiler id="App">
        <YourComponent />
      </ComponentProfiler>
    </div>
  )
}

方式四:使用带日志的 Hook

需要收集日志但不想使用组件时:

import { usePerformanceMonitorWithLogger } from '@ddll/react-performance-monitor'

function App() {
  const {
    ComponentProfiler,
    monitorActive,
    logs,
    clearLogs,
  } = usePerformanceMonitorWithLogger({
    maxLogs: 100,
    onLog: (log) => {
      console.log('性能警告:', log)
    },
  })

  return (
    <div>
      <ComponentProfiler id="App">
        <YourApp />
      </ComponentProfiler>
      
      {/* 自定义日志显示 */}
      <div>
        {logs.map(log => (
          <div key={log.id}>{log.message}</div>
        ))}
      </div>
    </div>
  )
}

配置选项

const { ComponentProfiler } = useReactPerformanceMonitor({
  // 启用/禁用监控模块
  enableMemoryMonitor: true,
  enableDOMMonitor: true,
  enableRenderMonitor: true,
  
  // DOM 监控的根节点选择器(可选)
  // 如果不指定,默认尝试 #root 或 #app,如果都找不到则使用 document.body
  domRootSelector: '#root',  // 例如: '#root', '#app', '.app-container' 等
  
  // 内存检查间隔(毫秒)
  memoryCheckInterval: 5000,
  
  // 警告阈值
  warnThreshold: {
    renderCount: 50,      // 组件渲染超过50次警告
    renderTime: 16,        // 单次渲染超过16ms警告
    memoryIncrease: 10,    // 内存增长超过10MB警告
    domMutations: 100,      // 1秒内DOM变更超过100次警告
  },
  
  // 自定义警告回调
  onWarning: (warning) => {
    console.log('性能警告:', warning)
    // 可以发送到监控平台
  },
  
  // 自定义日志(可选)
  logger: {
    log: (...args) => console.log(...args),
    warn: (...args) => console.warn(...args),
    error: (...args) => console.error(...args),
  },
})

使用 HOC 方式

import { withProfiler, ReactPerformanceMonitor } from '@ddll/react-performance-monitor'

// 创建监控实例
const monitor = new ReactPerformanceMonitor({
  enableRenderMonitor: true,
})
monitor.init()

// 包装组件
const MonitoredComponent = withProfiler(MyComponent, monitor)

// 使用
function App() {
  return <MonitoredComponent />
}

获取性能报告

import { useReactPerformanceMonitor, useMonitorReport } from '@ddll/react-performance-monitor'

function App() {
  const { ComponentProfiler, monitorActive, getReport } = useReactPerformanceMonitor()
  const { report } = useMonitorReport(monitorActive, getReport)
  
  return (
    <div>
      <ComponentProfiler id="App">
        <YourComponent />
      </ComponentProfiler>
      
      {report && (
        <div>
          <h3>渲染统计</h3>
          <pre>{JSON.stringify(report.renders, null, 2)}</pre>
          
          <h3>内存统计</h3>
          <pre>{JSON.stringify(report.memory, null, 2)}</pre>
          
          <h3>DOM 统计</h3>
          <pre>{JSON.stringify(report.dom, null, 2)}</pre>
        </div>
      )}
    </div>
  )
}

API 文档

PerformanceMonitorProvider

性能监控提供者组件,最简单的使用方式。

Props:

| 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | children | React.ReactNode | - | 子组件(必需) | | enabled | boolean | process.env.NODE_ENV === 'development' | 是否启用监控 | | autoStart | boolean | true | 是否自动启动监控 | | showControlPanel | boolean | false | 是否显示控制面板 | | componentId | string | 'App' | 组件 ID | | enableMemoryMonitor | boolean | true | 是否启用内存监控 | | enableDOMMonitor | boolean | true | 是否启用 DOM 监控 | | enableRenderMonitor | boolean | true | 是否启用渲染监控 | | memoryCheckInterval | number | 5000 | 内存检查间隔(毫秒) | | warnThreshold | Object | - | 警告阈值配置 | | onWarning | Function | - | 警告回调函数 | | logger | Object | - | 自定义日志对象 |

示例:

// 基础使用(开发环境自动启用)
<PerformanceMonitorProvider>
  <YourApp />
</PerformanceMonitorProvider>

// 显示控制面板
<PerformanceMonitorProvider showControlPanel={true}>
  <YourApp />
</PerformanceMonitorProvider>

// 自定义配置
<PerformanceMonitorProvider
  enabled={true}
  warnThreshold={{
    renderCount: 30,
    renderTime: 20,
    memoryIncrease: 5,
    domMutations: 50,
  }}
  onWarning={(warning) => {
    console.log('性能警告:', warning)
  }}
>
  <YourApp />
</PerformanceMonitorProvider>

useReactPerformanceMonitor(options)

React Hook,用于管理性能监控。

参数:

  • options (Object): 配置选项,见上方配置选项说明

返回值:

  • monitorActive (boolean): 监控是否激活
  • setMonitorActive (Function): 设置监控状态
  • startMonitor (Function): 启动监控
  • stopMonitor (Function): 停止监控
  • toggleMonitor (Function): 切换监控状态
  • clearData (Function): 清空监控数据
  • getReport (Function): 获取性能报告
  • ComponentProfiler (Component): Profiler 组件
  • monitor (ReactPerformanceMonitor): 监控实例

ReactPerformanceMonitor

核心监控类。

方法:

  • init(): 初始化监控
  • destroy(): 销毁监控
  • recordRender(componentName, phase, actualDuration, baseDuration): 记录组件渲染
  • getReport(): 获取性能报告
  • clear(): 清空数据

createProfiler(monitor)

创建 Profiler 组件。

参数:

  • monitor (ReactPerformanceMonitor): 监控实例

返回值:

  • ComponentProfiler (Component): Profiler 组件

withProfiler(Component, monitor, componentId?)

高阶组件,为组件添加性能监控。

参数:

  • Component (Component): 要监控的组件
  • monitor (ReactPerformanceMonitor): 监控实例
  • componentId (string, 可选): 组件 ID

返回值:

  • 包装后的组件

useMonitorReport(monitorActive, getReport, updateInterval?)

Hook,用于定期更新性能报告。

参数:

  • monitorActive (boolean): 监控是否激活
  • getReport (Function): 获取报告的函数
  • updateInterval (number, 可选): 更新间隔,默认 2000ms

返回值:

  • report (Object): 性能报告
  • setReport (Function): 手动设置报告

报告结构

{
  renders: [
    {
      component: "ComponentName",
      count: 10,
      avgDuration: "5.23",
      totalTime: "52.30",
      warning: false
    }
  ],
  memory: {
    current: {
      used: "50.23 MB",
      total: "100.45 MB",
      limit: "2048.00 MB"
    },
    trend: {
      increase: "5.23 MB",
      duration: "30 秒"
    },
    snapshots: [...]
  },
  dom: {
    total: 150,
    recent: [...],
    byTarget: [...]
  },
  timestamp: 1234567890
}

最佳实践

  1. 仅用于开发环境:在生产环境禁用或移除监控代码
  2. 按需启用:只在需要调试性能问题时启用监控
  3. 合理设置阈值:根据项目实际情况调整警告阈值
  4. 集成到开发工具:可以将警告信息发送到监控平台或开发工具

注意事项

  • performance.memory API 仅在 Chrome 浏览器中可用
  • MutationObserver 需要现代浏览器支持
  • 监控会消耗一定性能,建议仅在开发环境使用

版本历史

查看 CHANGELOG.md 了解版本更新历史。

贡献

欢迎提交 Issue 和 Pull Request!

相关链接

许可证

MIT