/ hooks / useMemoryUsage.ts
useMemoryUsage.ts
 1  import { useState } from 'react'
 2  import { useInterval } from 'usehooks-ts'
 3  
 4  export type MemoryUsageStatus = 'normal' | 'high' | 'critical'
 5  
 6  export type MemoryUsageInfo = {
 7    heapUsed: number
 8    status: MemoryUsageStatus
 9  }
10  
11  const HIGH_MEMORY_THRESHOLD = 1.5 * 1024 * 1024 * 1024 // 1.5GB in bytes
12  const CRITICAL_MEMORY_THRESHOLD = 2.5 * 1024 * 1024 * 1024 // 2.5GB in bytes
13  
14  /**
15   * Hook to monitor Node.js process memory usage.
16   * Polls every 10 seconds; returns null while status is 'normal'.
17   */
18  export function useMemoryUsage(): MemoryUsageInfo | null {
19    const [memoryUsage, setMemoryUsage] = useState<MemoryUsageInfo | null>(null)
20  
21    useInterval(() => {
22      const heapUsed = process.memoryUsage().heapUsed
23      const status: MemoryUsageStatus =
24        heapUsed >= CRITICAL_MEMORY_THRESHOLD
25          ? 'critical'
26          : heapUsed >= HIGH_MEMORY_THRESHOLD
27            ? 'high'
28            : 'normal'
29      setMemoryUsage(prev => {
30        // Bail when status is 'normal' — nothing is shown, so heapUsed is
31        // irrelevant and we avoid re-rendering the whole Notifications subtree
32        // every 10 seconds for the 99%+ of users who never reach 1.5GB.
33        if (status === 'normal') return prev === null ? prev : null
34        return { heapUsed, status }
35      })
36    }, 10_000)
37  
38    return memoryUsage
39  }