Created
March 22, 2024 07:07
-
-
Save dusanmarsa/394dc9c33a99900c138528cce7b40cb0 to your computer and use it in GitHub Desktop.
React hook for measuring Interaction to Next Pain (INP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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