Skip to content

Instantly share code, notes, and snippets.

@dusanmarsa
Created March 22, 2024 07:07
Show Gist options
  • Save dusanmarsa/394dc9c33a99900c138528cce7b40cb0 to your computer and use it in GitHub Desktop.
Save dusanmarsa/394dc9c33a99900c138528cce7b40cb0 to your computer and use it in GitHub Desktop.
React hook for measuring Interaction to Next Pain (INP)
import { useEffect } from 'react'
type PerformanceEntryEnhanced = PerformanceEntry & {
interactionId?: string
}
let worstInp = 0
const useINPMonitor = () => {
if (
typeof window === 'undefined' ||
!('PerformanceObserver' in window) ||
process.env.NODE_ENV !== 'development'
) {
return null;
}
useEffect(() => {
const observer = new PerformanceObserver((list) => {
for (let entry of list.getEntries()) {
if (!(entry as PerformanceEntryEnhanced)?.interactionId) continue
worstInp = Math.max(entry.duration, worstInp)
const entryInfo = {
type: 'Interaction',
event: entry.name,
duration: entry.duration,
worstInp,
}
// if (entryInfo.duration <= 40) continue
if (entryInfo.duration >= 200) {
console.warn(entryInfo)
continue
}
console.info(entryInfo)
}
})
observer.observe({
type: 'event',
durationThreshold: 0, // 16 minimum by spec
buffered: true,
} as AnyType)
}, [])
}
export default useINPMonitor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment