File size: 1,293 Bytes
064bfd6 | 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 | import { useState } from 'react'
import { useInterval } from 'usehooks-ts'
export type MemoryUsageStatus = 'normal' | 'high' | 'critical'
export type MemoryUsageInfo = {
heapUsed: number
status: MemoryUsageStatus
}
const HIGH_MEMORY_THRESHOLD = 1.5 * 1024 * 1024 * 1024 // 1.5GB in bytes
const CRITICAL_MEMORY_THRESHOLD = 2.5 * 1024 * 1024 * 1024 // 2.5GB in bytes
/**
* Hook to monitor Node.js process memory usage.
* Polls every 10 seconds; returns null while status is 'normal'.
*/
export function useMemoryUsage(): MemoryUsageInfo | null {
const [memoryUsage, setMemoryUsage] = useState<MemoryUsageInfo | null>(null)
useInterval(() => {
const heapUsed = process.memoryUsage().heapUsed
const status: MemoryUsageStatus =
heapUsed >= CRITICAL_MEMORY_THRESHOLD
? 'critical'
: heapUsed >= HIGH_MEMORY_THRESHOLD
? 'high'
: 'normal'
setMemoryUsage(prev => {
// Bail when status is 'normal' — nothing is shown, so heapUsed is
// irrelevant and we avoid re-rendering the whole Notifications subtree
// every 10 seconds for the 99%+ of users who never reach 1.5GB.
if (status === 'normal') return prev === null ? prev : null
return { heapUsed, status }
})
}, 10_000)
return memoryUsage
}
|