react-native-spectra
v1.0.3
Published
Comprehensive, real-time in-app performance monitoring & telemetry HUD for React Native applications.
Downloads
686
Maintainers
Readme
react-native-spectra
A high-performance, real-time telemetry engine and in-app visual monitoring HUD for React Native applications. Compatible with both the legacy Bridge (Old Architecture) and TurboModules / Fabric (New Architecture).
Overview
react-native-spectra delivers deep runtime visibility into React Native applications without external server dependencies or heavy bundle overhead. It actively monitors JavaScript thread responsiveness, frame rates, network latency, component render trees, memory allocation, and app lifecycle state.
Ecosystem & Architecture Support
| Environment / Architecture | Project Type | Support Status | Notes | | :--- | :--- | :--- | :--- | | Expo Go | Expo Managed | Supported | 100% Plug-and-Play, no native prebuild needed | | Expo Managed Workflow | Expo | Supported | Compatible with EAS Build and Expo SDK | | Expo Bare Workflow | Expo | Supported | Fully compatible | | React Native CLI (iOS / Android) | RN CLI | Supported | Standard iOS & Android projects | | New Architecture (TurboModules & Fabric) | RN 0.68+ | Supported | JSI & Fabric frame rate timing | | Old Architecture (Legacy Bridge) | RN Standard | Supported | Microtask queue fallbacks | | JS Engines (Hermes, JSC, V8) | All | Supported | Hermes memory profiling & JSC support |
Installation Guide
For React Native CLI Projects
npm install react-native-spectra
# or
yarn add react-native-spectraFor Expo Projects (Go, Managed, Bare)
npx expo install react-native-spectraCore Capabilities
1. JavaScript Thread Responsiveness (JSLagMonitor)
Detects event loop lag caused by long-running synchronous JavaScript computations, microtask queue congestion, or excessive state updates.
2. Frame Rate & Dropped Frame Analysis (FPSMonitor)
Calculates real-time frames per second (FPS), minimum FPS, average FPS, and total dropped frames against target 60 FPS refresh budgets.
3. Network Traffic Interception (NetworkMonitor)
Monkey-patches global fetch and XMLHttpRequest instances to log request method, target URL, duration, status codes, payload sizes, and network failure diagnostics.
4. Component Render Profiling (SpectraProfiler)
Measures React component render duration, base duration, render phase (mount vs update), and render count using React.Profiler. Flags render durations exceeding the 16ms frame budget.
5. Custom Code Path Tracing (useSpectraTrace, spectra.mark, spectra.measure)
Provides high-precision performance marks and custom async execution profiling for critical business logic (e.g., checkout flows, feed loading, database reads).
6. Memory Allocation & Lifecycle Tracking (MemoryMonitor, AppLifecycleMonitor)
Tracks JS heap memory estimates, cold start duration, and application state transitions (active, background, inactive).
7. Automated Warning Engine (WarningEngine)
Evaluates telemetry against customizable performance thresholds and issues warnings for severe frame drops, API slowdowns, component bottlenecks, and high JS lag.
8. Diagnostic Reports & Health Score (spectra.generateReport)
Computes an aggregate app health score (0-100) and exports structured JSON performance diagnostic reports for session debugging.
9. In-App Visual Dev HUD (SpectraOverlay)
Includes a sleek dark-mode floating HUD pill and full-screen tabbed dashboard modal (Overview, Network, Components, Timeline, Reports) for direct inspection during development and QA testing.
Installation
npm install react-native-spectra
# or
yarn add react-native-spectra
# or
pnpm add react-native-spectraQuick Start
Wrap your application root with <SpectraProvider>:
import React from 'react';
import { SpectraProvider } from 'react-native-spectra';
import MainNavigation from './src/navigation/MainNavigation';
export default function App() {
return (
<SpectraProvider
config={{
enabled: __DEV__,
enableOverlay: true,
thresholds: {
jsLagWarningMs: 50,
networkSlowMs: 1500,
componentSlowRenderMs: 16,
},
}}
>
<MainNavigation />
</SpectraProvider>
);
}Complete Usage Guide
1. Component Profiling
Wrap components with <SpectraProfiler> or use withSpectraProfiler to track render metrics.
Using JSX Component Wrapper
import React from 'react';
import { SpectraProfiler } from 'react-native-spectra';
import FeedList from './FeedList';
export function HomeScreen() {
return (
<SpectraProfiler id="HomeScreenFeed">
<FeedList />
</SpectraProfiler>
);
}Using Higher-Order Component (HOC)
import React from 'react';
import { withSpectraProfiler } from 'react-native-spectra';
function UserProfileComponent(props) {
return <View>{/* Profile UI */}</View>;
}
export default withSpectraProfiler(UserProfileComponent, 'UserProfileComponent');2. Custom Traces with React Hooks
Use useSpectraTrace to profile async functions or user interactions.
import React from 'react';
import { Button } from 'react-native';
import { useSpectraTrace } from 'react-native-spectra';
export function PaymentScreen() {
const { measureAsync } = useSpectraTrace('process_payment');
const handlePayment = async () => {
await measureAsync(async () => {
await api.post('/charge', { amount: 5000 });
await syncUserData();
}, { currency: 'USD', gateway: 'Stripe' });
};
return <Button title="Pay Now" onPress={handlePayment} />;
}Component Lifecycle Mount Tracking
import { useSpectraMountTrace } from 'react-native-spectra';
export function DashboardScreen() {
// Automatically measures mount-to-unmount duration
useSpectraMountTrace('DashboardScreen');
return <View>{/* Dashboard UI */}</View>;
}3. Imperative Telemetry API (spectra)
The global spectra singleton provides direct access to telemetry collection, marks, and diagnostic generation.
import { spectra } from 'react-native-spectra';
// Initializing programmatically (if not using SpectraProvider)
spectra.init({
enabled: true,
enableOverlay: true,
});
// Performance Marks & Measures
spectra.mark('feed_fetch_start');
const data = await fetchFeed();
spectra.mark('feed_fetch_end');
spectra.measure('feed_fetch_duration', 'feed_fetch_start', 'feed_fetch_end');
// Custom Manual Trace
const traceId = spectra.startTrace('image_processing');
await processImage();
spectra.stopTrace(traceId, { resolution: '1080p' });
// Querying Telemetry Snapshot
const currentFPS = spectra.getFPS();
const jsLag = spectra.getJSLag();
const memory = spectra.getMemory();
const networkLogs = spectra.getNetworkRequests();
const warnings = spectra.getWarnings();
const healthScore = spectra.calculateHealthScore(); // Returns number 0-100
// Generate Complete Diagnostic Report
const report = spectra.generateReport();
console.log(JSON.stringify(report, null, 2));
// Reset telemetry session logs
spectra.clear();Configuration Reference
The SpectraConfig object passed to SpectraProvider or spectra.init() supports the following options:
interface SpectraConfig {
/** Enable or disable telemetry collection (Default: true) */
enabled?: boolean;
/** Enable or disable the floating HUD overlay UI (Default: true) */
enableOverlay?: boolean;
/** Intercept global fetch and XHR calls (Default: true) */
enableNetworkMonitoring?: boolean;
/** Monitor JS thread event loop lag (Default: true) */
enableJSLagMonitoring?: boolean;
/** Monitor frame rates and dropped frames (Default: true) */
enableFPSMonitoring?: boolean;
/** Poll JS heap memory metrics (Default: true) */
enableMemoryMonitoring?: boolean;
/** Threshold configurations for warning engine */
thresholds?: Partial<SpectraThresholds>;
/** Maximum log items kept in memory history (Default: 200) */
maxLogsHistory?: number;
/** Filter network URLs from tracking */
ignoredNetworkUrls?: (string | RegExp)[];
}Threshold Configurations (SpectraThresholds)
interface SpectraThresholds {
/** JS lag duration to trigger warning alert (Default: 50ms) */
jsLagWarningMs: number;
/** JS lag duration to trigger critical alert (Default: 150ms) */
jsLagCriticalMs: number;
/** FPS drop threshold for warning alert (Default: 45 FPS) */
fpsWarning: number;
/** FPS drop threshold for critical alert (Default: 30 FPS) */
fpsCritical: number;
/** API request duration threshold for slow network warning (Default: 1500ms) */
networkSlowMs: number;
/** Component render duration threshold for slow render warning (Default: 16ms) */
componentSlowRenderMs: number;
/** Estimated JS memory usage threshold for memory warning (Default: 120MB) */
memoryWarningMb: number;
}Telemetry Data Models
FPSMetric
interface FPSMetric {
fps: number;
minFps: number;
avgFps: number;
droppedFrames: number;
totalFrames: number;
timestamp: number;
}JSLagMetric
interface JSLagMetric {
lagMs: number;
maxLagMs: number;
avgLagMs: number;
status: 'healthy' | 'warning' | 'critical';
timestamp: number;
}NetworkMetric
interface NetworkMetric {
id: string;
url: string;
method: string;
status?: number;
duration: number;
requestSize?: number;
responseSize?: number;
timestamp: number;
error?: string;
responseType?: string;
}ComponentRenderMetric
interface ComponentRenderMetric {
id: string;
phase: 'mount' | 'update' | 'nested-update';
actualDuration: number;
baseDuration: number;
startTime: number;
commitTime: number;
renderCount: number;
avgDuration: number;
maxDuration: number;
isSlow: boolean;
lastRenderTimestamp: number;
}SpectraReport
interface SpectraReport {
generatedAt: string;
healthScore: number;
sessionDurationSec: number;
fps: { current: number; min: number; avg: number; droppedFrames: number };
jsLag: { currentMs: number; maxMs: number; avgMs: number };
memoryMb: number;
network: { totalRequests: number; failedRequests: number; avgLatencyMs: number; slowRequests: number };
components: { totalMonitored: number; slowRendersCount: number; slowestComponent?: { id: string; duration: number } };
warningsCount: { total: number; critical: number; warning: number };
recentWarnings: SpectraWarning[];
}License
MIT License. Developed for high-reliability React Native applications.
