useMemoryUsage.ts
hooks/useMemoryUsage.ts
40
Lines
1293
Bytes
3
Exports
2
Imports
10
Keywords
What this is
This page documents one file from the repository and includes its full source so you can read it without leaving the docs site.
Beginner explanation
This file is one piece of the larger system. Its name, directory, imports, and exports show where it fits. Start by reading the exports and related files first.
How it is used
Start from the exports list and related files. Those are the easiest clues for where this file fits into the system.
Expert explanation
Architecturally, this file intersects with memory-layers. It contains 40 lines, 2 detected imports, and 3 detected exports.
Important relationships
Detected exports
MemoryUsageStatusMemoryUsageInfouseMemoryUsage
Keywords
heapusedstatusnormalmemoryusagestatusmemoryusageinfomemoryusageprevusestateuseintervalhigh
Detected imports
reactusehooks-ts
Source notes
This page embeds the full file contents. Small or leaf files are still indexed honestly instead of being over-explained.
Full source
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
}