Skip to content

Commit

Permalink
docs: document reportWebVitalsFn stabilization fix
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielelpidio committed Dec 16, 2024
1 parent c998444 commit 94426b8
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/webVitals/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,27 @@ export { AxiomWebVitals } from './components';

export function useReportWebVitals(path?: string) {
const pathName = usePathname();

/**
* Refs allows us to stabilize the path name so that we can properly stabilize the reportWebVitalsFn
*/

const stabilizedPath = useRef(path || pathName);

/**
* If the path changes, we update the stabilizedPath ref
*/
if (typeof path === 'string' && path !== stabilizedPath.current) {
stabilizedPath.current = pathName;
} else if (typeof path === 'string' && path === stabilizedPath.current) {
stabilizedPath.current = path;
}

/**
* Stabilizing the reportWebVitalsFn avoids reporting the same metrics from multiple paths, it happens because internally
* the useReportWebVitals from next uses a useEffect to report the metrics, and the reportWebVitalsFn is passed as a dependency
* to the useEffect, so when the path changes, the useEffect is re-run, and the same metrics are reported again.
*/
const reportWebVitalsFn: Parameters<typeof useNextReportWebVitals>[0] = useCallback(
(metric) => reportWebVitalsWithPath(metric, stabilizedPath.current),
[]
Expand Down

0 comments on commit 94426b8

Please sign in to comment.