react-native-perf-stats
v1.0.0
Published
React Native library for real-time performance monitoring with customizable overlay graphs, memory, CPU, FPS, and more.
Maintainers
Readme
react-native-perf-stats
Table of Contents
- Features
- Installation
- Quick Start
- API Reference
- Value Templates
- Platform Differences
- Creating a Custom Graph
- Example
- Performance Considerations
- Troubleshooting
- Contributing
- License
Features
🚀 Real-time Performance Monitoring
- Memory usage tracking
- FPS monitoring (Platform-specific)
- Frame drops and stutters detection (Android)
- CPU usage monitoring (iOS)
- View count tracking (iOS)
📱 Cross-Platform Support
- Built with TurboModule for optimal performance
- Platform-specific optimizations for Android and iOS
- Unified API with platform-aware graph types
🎨 Customizable UI
- Draggable overlay graphs
- Fully customizable colors, sizes, and styles
- Template-based value formatting
- Real-time updates with smooth animations
🔧 Developer Tools
- Built-in thread blocking utilities for testing
- TypeScript support with comprehensive types
- Easy integration with existing projects
Installation
npm install react-native-perf-statsiOS Setup
For iOS, you need to run pod install:
cd ios && pod installAndroid Setup
No additional setup required for Android.
Quick Start
import React, { useEffect } from 'react';
import { Platform } from 'react-native';
import { createGraph, GraphTypes } from 'react-native-perf-stats';
export default function App() {
useEffect(() => {
// Create a memory graph (available on both platforms)
createGraph(GraphTypes.MEMORY, {
width: 300,
height: 200,
containerBackgroundColor: '#1a202c',
graphBackgroundColor: '#2d3748',
graphLineColor: '#68d391',
topTextColor: '#68d391',
valueTemplate: 'RAM: {{ current }} MB',
});
// Platform-specific graphs
if (Platform.OS === 'ios') {
createGraph(GraphTypes.CPU, {
width: 300,
height: 200,
valueTemplate: 'CPU: {{ current }}%',
});
} else {
createGraph(GraphTypes.FPS, {
width: 300,
height: 200,
valueTemplate: 'FPS: {{ current }}',
});
}
}, []);
return (
// Your app content
);
}API Reference
Graph Types
Use the GraphTypes constants for type safety:
import { GraphTypes } from 'react-native-perf-stats';Common (Both Platforms):
GraphTypes.MEMORY- Memory usage in MB
Android Specific:
GraphTypes.FPS- Frames per secondGraphTypes.FRAMES_DROPPED- Dropped frames countGraphTypes.FRAME_STUTTERS- Frame stutter count
iOS Specific:
GraphTypes.CPU- CPU usage percentageGraphTypes.UI_FPS- UI thread FPSGraphTypes.JS_FPS- JavaScript thread FPSGraphTypes.VIEW_COUNT- Total view countGraphTypes.VISIBLE_VIEW_COUNT- Visible view count
Core Methods
createGraph(graphId, config)
Creates and displays a performance graph.
import { createGraph, GraphTypes } from 'react-native-perf-stats';
const success = await createGraph(GraphTypes.MEMORY, {
width: 400,
height: 250,
containerBackgroundColor: '#1a202c',
graphBackgroundColor: '#2d3748',
graphLineColor: '#68d391',
topTextColor: '#68d391',
valueTemplate: 'Memory: {{ current }} MB ({{ min }} - {{ max }})',
defaultMaxValue: 512,
dataPointWidth: 2.0,
containerPadding: 8,
graphOpacity: 0.9,
});Parameters:
graphId(string | GraphType): Unique identifier or GraphType constantconfig(GraphConfig): Configuration object
GraphConfig Properties:
width?: number- Graph width in pixelsheight?: number- Graph height in pixelsdataPointWidth?: number- Width of each data point (default: 2.0)valueFormat?: string- Number format (e.g., "%.1f", "%d")valueTemplate?: string- Display template with placeholdersdefaultMaxValue?: number- Default maximum value for scalingcontainerBackgroundColor?: string- Background colorgraphBackgroundColor?: string- Graph area backgroundgraphLineColor?: string- Line/fill colortopTextColor?: string- Text colorcontainerPadding?: number- Padding around graphgraphOpacity?: number- Graph transparency (0-1)
updateGraph(graphId, value)
Manually update a graph with a custom value.
import { updateGraph, GraphTypes } from 'react-native-perf-stats';
const success = await updateGraph(GraphTypes.MEMORY, 128.5);removeGraph(graphId)
Remove a specific graph.
import { removeGraph, GraphTypes } from 'react-native-perf-stats';
const success = await removeGraph(GraphTypes.MEMORY);removeAllGraphs()
Remove all graphs and stop monitoring.
import { removeAllGraphs } from 'react-native-perf-stats';
const success = await removeAllGraphs();Event-based Stats Monitoring
You can monitor real-time performance stats (memory, CPU, FPS, etc.) without displaying any graphs by subscribing to the onStatsUpdated event.
Option 1: Manual Event Subscription
import PerfStats from 'react-native-perf-stats';
import type { EventSubscription } from 'react-native';
const eventListenerRef = useRef<null | EventSubscription>(null);
useEffect(() => {
setIsActive(true);
eventListenerRef.current = PerfStatsNative?.onStatsUpdated((event: any) =>
console.log(event)
);
// Start monitoring
PerfStatsNative.startMonitoring();
return () => {
eventListenerRef.current?.remove();
PerfStatsNative.stopMonitoring();
};
}, []);Option 2: React Hook (Recommended)
import { usePerfStats, startMonitoring, stopMonitoring } from 'react-native-perf-stats';
function MyStatsPanel() {
const [stats] = usePerfStats();
// Optionally, call startMonitoring/stopMonitoring manually if you want more control
if (!stats) return <Text>Loading...</Text>;
return (
<View>
<Text>Memory: {stats.memory}</Text>
<Text>CPU: {stats.cpu}</Text>
<Text>UI FPS: {stats.uiFps}</Text>
<Text>JS FPS: {stats.jsFps}</Text>
{/* ...other stats */}
</View>
);
}- The hook will automatically start and stop monitoring when the component mounts/unmounts.
- You can use the event system even if you do not display any graphs.
Testing Utilities
blockJsThread(milliseconds)
Block the JavaScript thread for testing purposes.
import { blockJsThread } from 'react-native-perf-stats';
// Block JS thread for 3 seconds
await blockJsThread(3000);blockUiThread(milliseconds)
Block the UI/main thread for testing purposes.
import { blockUiThread } from 'react-native-perf-stats';
// Block UI thread for 2 seconds
const success = await blockUiThread(2000);Value Templates
Use template strings to customize how values are displayed:
// Basic value
valueTemplate: '{{ current }}'
// With units
valueTemplate: 'Memory: {{ current }} MB'
// With min/max
valueTemplate: 'FPS: {{ current }} ({{ min }} - {{ max }})'
// Complex template
valueTemplate: 'CPU: {{ current }}% | Peak: {{ max }}%'Available placeholders:
{{ current }}- Current value{{ min }}- Minimum recorded value{{ max }}- Maximum recorded value
Platform Differences
Android
- Uses FpsDebugFrameCallback for frame metrics
- Monitors memory via Runtime
- Tracks frame drops and stutters
iOS
- Uses CADisplayLink for FPS monitoring
- Monitors CPU via host statistics
- Tracks memory via task_info
- Separate UI and JS FPS monitoring
- View hierarchy tracking
Creating a Custom Graph
You can create your own custom performance graph with a unique ID and update its value programmatically. This is useful for visualizing any numeric metric in real time.
Example
import { createGraph, updateGraph } from 'react-native-perf-stats';
// Create a custom graph
const customId = `custom-metric`;
createGraph(customId, {
width: 300,
height: 150,
containerBackgroundColor: '#2c5282',
graphBackgroundColor: '#3182ce',
graphLineColor: '#90cdf4',
topTextColor: '#90cdf4',
valueTemplate: 'Custom: {{ current }} ({{ min }} - {{ max }})',
defaultMaxValue: 200,
});
// Update the custom graph value (e.g., in a timer or callback)
setInterval(() => {
const value = Math.random() * 200;
updateGraph(customId, value);
}, 1000);- You can create as many custom graphs as you like, each with a unique ID.
- Use
updateGraphto push new values to your custom graph at any time.
Example
For a complete implementation example, see example/src/App.tsx which demonstrates:
- Platform-specific graph creation
- Custom styling and configuration
- Interactive testing with thread blocking
- Graph management (create/update/remove)
- SafeAreaView integration
Performance Considerations
- Graphs update automatically every second
- Minimal impact on app performance
- Efficient native implementations
- Automatic cleanup when graphs are removed
Troubleshooting
Graph not appearing
- Ensure you're calling
createGraphafter component mount - Check that the graph ID doesn't already exist
- Verify platform-specific graph types
Performance issues
- Limit the number of concurrent graphs
- Use appropriate
defaultMaxValuefor better scaling - Remove graphs when not needed with
removeAllGraphs()
Contributing
See the contributing guide to learn how to contribute to the repository and the development workflow.
License
MIT
Made with create-react-native-library
