Skip to content

Commit

Permalink
use ref for report callback
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Sep 13, 2021
1 parent bc02854 commit f0de779
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
6 changes: 3 additions & 3 deletions docs/advanced-features/measuring-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ The rest of this documentation describes the built-in relayer Next.js Analytics

## Build Your Own

There're 2 ways of defining web vitals metrics reporting handler.
There're 2 ways to define your metrics handler.

**First one**, you can create a [custom App](/docs/advanced-features/custom-app.md) component and define a `reportWebVitals` function as global web vitals metrics handler:
One way is to create a [custom App](/docs/advanced-features/custom-app.md) component and define a `reportWebVitals` function:

```js
// pages/_app.js
Expand All @@ -30,7 +30,7 @@ function MyApp({ Component, pageProps }) {
export default MyApp
```

**Another way** is to use the React hook version of `reportWebVitals`, using `useWebVitalsReport` and passing a callback to receive web vital metrics:
Alternatively you can use the `useWebVitalsReport` hook API, with a callback function to receive metric reports:

```js
// pages/home.js
Expand Down
11 changes: 6 additions & 5 deletions packages/next/vitals/vitals.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from 'react'
import { useEffect, useRef } from 'react'
import { NextWebVitalsMetric } from '../pages/_app'

type ReportWebVitalsCallback = (webVitals: NextWebVitalsMetric) => any
Expand All @@ -11,14 +11,15 @@ export function trackWebVitalMetric(metric: NextWebVitalsMetric) {
}

export function useWebVitalsReport(callback: ReportWebVitalsCallback) {
const callbackRef = useRef(callback)
useEffect(() => {
if (metrics.length) {
metrics.forEach((metric) => callback(metric))
metrics.forEach((metric) => callbackRef.current(metric))
}

webVitalsCallbacks.add(callback)
webVitalsCallbacks.add(callbackRef.current)
return () => {
webVitalsCallbacks.delete(callback)
webVitalsCallbacks.delete(callbackRef.current)
}
}, [callback])
}, [])
}

0 comments on commit f0de779

Please sign in to comment.