Capítulo 383 de 456

useReportWebVitals

Core Idea

useReportWebVitals (from next/web-vitals) reports Core Web Vitals and Next.js-specific timing metrics to any analytics service.

Key Concepts

  • Callback stability: the function reference passed must not change between renders, or metrics get reported as duplicates.
  • metric object: id, name, delta, entries, navigationType ("navigate", "reload", "prerender", "back-forward", "back-forward-cache", "restore"), rating ("good"/"needs-improvement"/"poor"), value.
  • Web Vitals covered: TTFB, FCP, LCP, FID, CLS, INP.
  • Custom Next.js metrics: Next.js-hydration, Next.js-route-change-to-render, Next.js-render.

Code Examples

import { useReportWebVitals } from 'next/web-vitals'

const logWebVitals = (metric) => {
  console.log(metric)
}

function MyApp({ Component, pageProps }) {
  useReportWebVitals(logWebVitals)
  return <Component {...pageProps} />
}
  • O que demonstra: minimal setup logging every metric from _app.js.
function postWebVitals(metric) {
  const body = JSON.stringify(metric)
  const url = 'https://example.com/analytics'
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body)
  } else {
    fetch(url, { body, method: 'POST', keepalive: true })
  }
}

useReportWebVitals(postWebVitals)
  • O que demonstra: sending metrics to an external endpoint via sendBeacon with fetch fallback.

Reference Tables

metric fieldMeaning
idunique id per page load
namemetric name (TTFB, FCP, LCP, FID, CLS, INP, or custom)
deltachange from previous value
entriesrelated PerformanceEntry[]
navigationTypehow navigation was triggered
ratinggood | needs-improvement | poor
valuemeasured value (ms)

Anti-patterns

  • Passing an inline/new function each render: causes duplicate metric reports; define the callback outside the render or memoize it.
  • Using CLS value directly without scaling for GA: Google Analytics expects Math.round(value * 1000) for CLS since GA requires integers.

Key Takeaways

  1. Must be called from pages/_app.js to capture app-wide vitals.
  2. Custom Next.js timing metrics (hydration, route-change-to-render, render) work in any browser supporting the User Timing API.
  3. Switch on metric.name to route different vitals to different handlers.

Connects To

  • Script: both concern client-side performance; Script controls loading strategy, this reports the resulting metrics.
  • _app.js (Pages Router): the required host file for this hook.