How can I display web vitals metrics into my page footer with nextjs and react hook?

At the end I dispatch a new CustomEvent and useEffect to addEventListener into this custom event. Here is the code:

_app.js

export function reportWebVitals(result) {
  if (result.name === "FCP") {
    dispatchFcpEvent(result);
  }
};

Metric.js

let fcpEvent = null;

export const dispatchFcpEvent = (fcp) => {
  fcpEvent = new CustomEvent('fcpTime', { detail: fcp.value });
  window.dispatchEvent(fcpEvent);
}

const Copyright = () => {
  const [fcpTime, setFcpTime] = useState();

  if (typeof window !== "undefined") {
    const onFcpTimeUpdate = (e) => {
      setFcpTime(e.detail);
      window.removeEventListener('fcpTime', onFcpTimeUpdate, false);
    };
    useEffect(() => {
      window.addEventListener('fcpTime', onFcpTimeUpdate);
    }, []);
  }

  // return below
  ...
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top