Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | 46x 46x 46x 46x 46x 46x 46x 46x 46x 2x 2x 44x 38x 46x 46x 1x 1x 45x 30x 46x 13x 46x 26x 2x 2x 2x 2x 2x 46x 46x | import { useCallback, useEffect, useRef } from "react";
import { useMemoryMonitor } from "@usefy/use-memory-monitor";
import type {
MemoryMonitorHeadlessOptions,
MemoryMonitorHeadlessReturn,
LeakAnalysisData,
} from "./types";
import { AUTO_GC_COOLDOWN_MS } from "./constants";
/**
* Headless memory monitoring hook for production environments
*
* This hook provides memory monitoring functionality without any UI,
* perfect for production environments where you want to track memory
* usage and trigger callbacks without showing a visible panel.
*
* @example
* ```tsx
* function App() {
* const {
* memory,
* usagePercentage,
* severity,
* isLeakDetected,
* requestGC,
* } = useMemoryMonitorHeadless({
* warningThreshold: 70,
* criticalThreshold: 90,
* onWarning: (data) => {
* console.warn('Memory warning:', data);
* analytics.track('memory_warning', data);
* },
* onCritical: (data) => {
* console.error('Critical memory:', data);
* analytics.track('memory_critical', data);
* },
* });
*
* return <YourApp />;
* }
* ```
*/
export function useMemoryMonitorHeadless(
options: MemoryMonitorHeadlessOptions = {}
): MemoryMonitorHeadlessReturn {
const {
interval = 1000,
enableHistory = false,
historySize = 50,
warningThreshold = 70,
criticalThreshold = 90,
autoGCThreshold = null,
enableAutoGC = false,
enableLeakDetection = false,
leakSensitivity = "medium",
onWarning,
onCritical,
onLeakDetected,
onAutoGC,
} = options;
// Track last auto-GC timestamp for cooldown
const lastAutoGCRef = useRef<number>(0);
// Track if warning/critical callbacks have been fired for current state
const warningFiredRef = useRef(false);
const criticalFiredRef = useRef(false);
// Use the core memory monitor hook
const {
memory,
isSupported,
usagePercentage,
trend,
leakProbability,
requestGC,
} = useMemoryMonitor({
interval,
enableHistory,
historySize,
leakDetection: {
enabled: enableLeakDetection,
sensitivity: leakSensitivity,
},
});
// Calculate current severity
const severity =
usagePercentage !== null
? usagePercentage >= criticalThreshold
? "critical"
: usagePercentage >= warningThreshold
? "warning"
: "normal"
: "normal";
// Check if leak is detected
const isLeakDetected =
enableLeakDetection && trend === "increasing" && leakProbability >= 50;
// Handle warning callback
useEffect(() => {
if (severity === "warning" && !warningFiredRef.current && onWarning) {
warningFiredRef.current = true;
onWarning({
memory: {
heapUsed: memory?.heapUsed ?? 0,
heapTotal: memory?.heapTotal ?? 0,
heapLimit: memory?.heapLimit ?? 0,
timestamp: Date.now(),
},
usagePercentage: usagePercentage ?? 0,
threshold: warningThreshold,
timestamp: Date.now(),
});
} else if (severity !== "warning") {
warningFiredRef.current = false;
}
}, [severity, memory, usagePercentage, warningThreshold, onWarning]);
// Handle critical callback
useEffect(() => {
if (severity === "critical" && !criticalFiredRef.current && onCritical) {
criticalFiredRef.current = true;
onCritical({
memory: {
heapUsed: memory?.heapUsed ?? 0,
heapTotal: memory?.heapTotal ?? 0,
heapLimit: memory?.heapLimit ?? 0,
timestamp: Date.now(),
},
usagePercentage: usagePercentage ?? 0,
threshold: criticalThreshold,
timestamp: Date.now(),
});
} else if (severity !== "critical") {
criticalFiredRef.current = false;
}
}, [severity, memory, usagePercentage, criticalThreshold, onCritical]);
// Handle leak detection callback
useEffect(() => {
Iif (isLeakDetected && onLeakDetected) {
const analysis: LeakAnalysisData = {
isLeaking: true,
probability: leakProbability,
trend,
recommendation:
leakProbability >= 70
? "High probability of memory leak. Check for unsubscribed subscriptions, detached event listeners, or closure leaks."
: leakProbability >= 40
? "Moderate risk of memory leak. Monitor memory usage and consider taking snapshots to identify the source."
: "Low risk of memory leak. Continue monitoring.",
};
onLeakDetected(analysis);
}
}, [isLeakDetected, leakProbability, trend, onLeakDetected]);
// Handle auto-GC
useEffect(() => {
if (
enableAutoGC &&
autoGCThreshold !== null &&
usagePercentage !== null &&
usagePercentage >= autoGCThreshold
) {
const now = Date.now();
Eif (now - lastAutoGCRef.current >= AUTO_GC_COOLDOWN_MS) {
lastAutoGCRef.current = now;
requestGC();
onAutoGC?.({
threshold: autoGCThreshold,
usage: usagePercentage,
timestamp: now,
});
}
}
}, [enableAutoGC, autoGCThreshold, usagePercentage, requestGC, onAutoGC]);
// Memoized requestGC
const handleRequestGC = useCallback(() => {
requestGC();
}, [requestGC]);
return {
memory: memory
? {
heapUsed: memory.heapUsed,
heapTotal: memory.heapTotal,
heapLimit: memory.heapLimit,
timestamp: Date.now(),
}
: null,
usagePercentage,
severity,
isLeakDetected,
leakProbability,
trend,
requestGC: handleRequestGC,
isSupported,
};
}
|