Skip to content
usefy

useMemoryMonitor

Browser & device

Advanced React hook for real-time browser memory monitoring

Install

$ npm install @usefy/use-memory-monitor

Quick start

useMemoryMonitor.tsx
import { useMemoryMonitor } from "@usefy/use-memory-monitor";

function MemoryMonitor() {
  const {
    heapUsed,
    heapTotal,
    heapLimit,
    isSupported,
    severity,
    formatted,
  } = useMemoryMonitor({
    interval: 1000,
    autoStart: true,
  });

  if (!isSupported) {
    return <div>Memory monitoring not supported in this browser</div>;
  }

  return (
    <div>
      <h2>Memory Usage</h2>
      <p>Heap Used: {formatted.heapUsed}</p>
      <p>Heap Total: {formatted.heapTotal}</p>
      <p>Heap Limit: {formatted.heapLimit}</p>
      <p>Severity: {severity}</p>
    </div>
  );
}

API reference

useMemoryMonitor(options?)

A hook that monitors browser memory usage in real-time with leak detection and threshold alerts.

Parameters

ParameterTypeDefaultDescription
optionsUseMemoryMonitorOptions{}Configuration options (see below)

Options (UseMemoryMonitorOptions)

OptionTypeDefaultDescription
intervalnumber5000Polling interval in milliseconds
autoStartbooleantrueStart monitoring automatically on mount
enabledbooleantrueEnable/disable the hook
enableHistorybooleanfalseRecord memory history into a circular buffer
historySizenumber50Maximum number of history entries
thresholdsThresholdOptionsSee belowWarning/critical usage thresholds
leakDetectionLeakDetectionOptionsSee belowLeak detection configuration
devModebooleanfalseEnable development-mode features
trackDOMNodesbooleanfalseTrack the document's DOM node count
trackEventListenersbooleanfalseEstimate the event listener count
logToConsolebooleanfalseLog updates to the console (with devMode)
disableInProductionbooleanfalseDisable monitoring in production builds
fallbackStrategyFallbackStrategy"dom-only"Fallback for browsers without the heap API
onUpdate(memory) => void-Called on each memory update
onWarning(data) => void-Called when the warning threshold is exceeded
onCritical(data) => void-Called when the critical threshold is exceeded
onLeakDetected(analysis) => void-Called when a memory leak is detected
onUnsupported(info) => void-Called when memory monitoring is not supported
Default Thresholds (ThresholdOptions)
{
  warning: 70,   // severity becomes "warning" at 70% of the heap limit
  critical: 90,  // severity becomes "critical" at 90% of the heap limit
}
Default Leak Detection (LeakDetectionOptions)
{
  enabled: false,         // opt in to enable leak analysis
  sensitivity: "medium",  // 'low' | 'medium' | 'high'
  windowSize: 20,         // number of recent samples to analyze
  threshold: undefined,   // optional custom growth threshold (bytes/sample)
}

Leak detection requires enableHistory: true so there are samples to analyze.

Returns UseMemoryMonitorReturn

PropertyTypeDescription
memoryMemoryInfo | nullCurrent memory information
heapUsednumber | nullUsed heap size in bytes
heapTotalnumber | nullTotal heap size in bytes
heapLimitnumber | nullHeap size limit in bytes
usagePercentagenumber | nullHeap usage as a percentage of the limit
domNodesnumber | nullDOM node count (when trackDOMNodes is enabled)
eventListenersnumber | nullEstimated listener count (when tracking)
isSupportedbooleanWhether memory monitoring is supported
isMonitoringbooleanWhether monitoring is currently active
isLeakDetectedbooleanWhether a memory leak is currently detected
severitySeverityCurrent severity level
supportLevelSupportLevel'full' | 'partial' | 'none'
availableMetricsreadonly AvailableMetric[]Metrics available in this browser
historyreadonly MemoryInfo[]Historical memory data (empty if history is off)
trendTrendMemory usage trend
leakProbabilitynumberCurrent leak probability (0–100)
formattedFormattedMemoryHuman-readable formatted values
start() => voidStart monitoring
stop() => voidStop monitoring
takeSnapshot(id: string) => MemorySnapshot | nullTake a named memory snapshot
compareSnapshots(id1: string, id2: string) => SnapshotDiff | nullCompare two named snapshots
clearHistory() => voidClear the history buffer
requestGC() => voidRequest garbage collection (hint only)

Types

Severity

type Severity = "normal" | "warning" | "critical";

Trend

type Trend = "stable" | "increasing" | "decreasing";

MemoryInfo

interface MemoryInfo {
  /** Used JS heap size in bytes */
  heapUsed: number;
  /** Total JS heap size in bytes */
  heapTotal: number;
  /** JS heap size limit in bytes */
  heapLimit: number;
  /** Timestamp when this measurement was taken */
  timestamp: number;
}

SnapshotDiff

interface SnapshotDiff {
  /** Difference in heap usage (bytes) */
  heapDelta: number;
  /** Percentage change in heap usage */
  heapPercentChange: number;
  /** Difference in DOM node count (if tracked) */
  domNodesDelta?: number;
  /** Difference in event listener count (if tracked) */
  eventListenersDelta?: number;
  /** Time elapsed between snapshots (ms) */
  timeDelta: number;
}

FormattedMemory

interface FormattedMemory {
  heapUsed: string;
  heapTotal: string;
  heapLimit: string;
  domNodes?: string;
  eventListeners?: string;
}

Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in browser & device