useWebVitals
Description and use case
useWebVitals provides live Core Web Vitals data and optional metric callbacks for analytics pipelines.
API signature
function useWebVitals(options?: UseWebVitalsOptions): WebVitalsState
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
options.onMetric | (metric: WebVitalMetric) => void | No | Callback fired whenever a metric is updated. |
options.enabled | boolean | No | Set false to disable subscriptions (useful for SSR/tests). |
Return value
| Field | Type | Description |
|---|---|---|
CLS | WebVitalMetric | null | Cumulative Layout Shift metric. |
LCP | WebVitalMetric | null | Largest Contentful Paint metric. |
INP | WebVitalMetric | null | Interaction to Next Paint metric. |
FCP | WebVitalMetric | null | First Contentful Paint metric. |
TTFB | WebVitalMetric | null | Time to First Byte metric. |
Live interactive demo (StackBlitz)
This demo uses an embedded StackBlitz sandbox. Load it inline or open it in a new tab.
Open demo in StackBlitzCode example
import {useWebVitals} from 'react-perf-hooks';
export function VitalsOverlay() {
const vitals = useWebVitals({
onMetric: (metric) => {
navigator.sendBeacon('/api/vitals', JSON.stringify(metric));
},
});
return <p>LCP: {vitals.LCP?.value ?? 'waiting'}</p>;
}