-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
vitals.ts
50 lines (41 loc) · 1.33 KB
/
vitals.ts
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
import { useEffect, useRef } from 'react'
import { NextWebVitalsMetric } from '../../pages/_app'
type ReportWebVitalsCallback = (webVitals: NextWebVitalsMetric) => any
export const webVitalsCallbacks = new Set<ReportWebVitalsCallback>()
let flushed = false
const metrics: NextWebVitalsMetric[] = []
export function getBufferedVitalsMetrics() {
return metrics
}
export function flushBufferedVitalsMetrics() {
flushed = true
metrics.length = 0
}
export function trackWebVitalMetric(metric: NextWebVitalsMetric) {
metrics.push(metric)
webVitalsCallbacks.forEach((callback) => callback(metric))
}
export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
const metricIndexRef = useRef(0)
if (process.env.NODE_ENV === 'development') {
if (flushed) {
console.error(
'The `useWebVitalsReport` hook was called too late -- did you use it inside of a <Suspense> boundary?'
)
}
}
useEffect(() => {
// Flush calculated metrics
const reportMetric = (metric: NextWebVitalsMetric) => {
callback(metric)
metricIndexRef.current = metrics.length
}
for (let i = metricIndexRef.current; i < metrics.length; i++) {
reportMetric(metrics[i])
}
webVitalsCallbacks.add(reportMetric)
return () => {
webVitalsCallbacks.delete(reportMetric)
}
}, [callback])
}