LoginSignup
43
21

More than 3 years have passed since last update.

CreateReactAppにWebVitals計測ライブラリが入ったので試してみた

Last updated at Posted at 2020-12-11

この記事はReact #2 Advent Calendar 2020の12日目の記事です

概要

  • 最近はNext.jsばかり使ってますが久しぶりにCreateReactAppを使ってみたらreportWebVitals.tsという見慣れないファイルが生成されていたのを見たのが今日の記事のきっかけです
  • Reactアプリの雛形生成ツールであるCreateReactAppはv4でWebVitalsの計測ライブラリがデフォルトで組み込まれるようになりました
  • せっかくなのでドキュメントに沿って少し試してみたいと思います

ファイルの確認

  • まずは生成されたコードを見てみましょう
  • create-react-appコマンドで雛形を生成します
npx create-react-app --template typescript web-vitals-sample
  • 生成されたファイルの一覧はこんな感じです
.
├── README.md
├── package.json
├── public
│   ├── favicon.ico
│   ├── index.html
│   ├── logo192.png
│   ├── logo512.png
│   ├── manifest.json
│   └── robots.txt
├── src
│   ├── App.css
│   ├── App.test.tsx
│   ├── App.tsx
│   ├── index.css
│   ├── index.tsx
│   ├── logo.svg
│   ├── react-app-env.d.ts
│   ├── reportWebVitals.ts
│   └── setupTests.ts
├── tsconfig.json
└── yarn.lock
  • reportWebVitals.tsが今回注目するファイルですね
  • 中身はこんな感じです
src/reportWebVitals.ts
import { ReportHandler } from 'web-vitals';

const reportWebVitals = (onPerfEntry?: ReportHandler) => {
  if (onPerfEntry && onPerfEntry instanceof Function) {
    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
      getCLS(onPerfEntry);
      getFID(onPerfEntry);
      getFCP(onPerfEntry);
      getLCP(onPerfEntry);
      getTTFB(onPerfEntry);
    });
  }
};

export default reportWebVitals;
  • web-vitalsというライブラリを使っていろいろ設定してくれています
  • web-vitalsはGoogleChromeが提供するWebVitals計測ライブラリですね
  • このライブラリの追加とセットアップを事前にやってくれているということのようです

使い方

  • 使い方はCreateReactAppのドキュメントに載っています
  • reportWebVitals.tsでexportされたreportWebVitalsを呼び出して引数に関数を渡して使います
    • 渡した関数が内部で呼び出され各種メトリクスが渡されます
  • サンプルにあるようにconsole.logを引数として渡してみます
src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root'),
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(console.log);
  • ページを表示するとコンソールにLCPなどのWebVitalsの指標が表示されました!

スクリーンショット 2020-12-11 18.14.37.png

function sendToAnalytics(metric: Metrics) {
  const body = JSON.stringify(metric);
  const url = 'https://example.com/analytics';

  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`
  if (navigator.sendBeacon) {
    navigator.sendBeacon(url, body);
  } else {
    fetch(url, { body, method: 'POST', keepalive: true });
  }
}

reportWebVitals(sendToAnalytics);
function sendToAnalytics({ id, name, value }) {
  ga('send', 'event', {
    eventCategory: 'Web Vitals',
    eventAction: name,
    eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    eventLabel: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate
  });
}

reportWebVitals(sendToAnalytics);

試してみた

  • 送信されたデータをDBに保存するAPIを作って適当にグラフ表示してみました
    • どういう風に集計するのが有用かはもうちょっとちゃんと考えないといけないですね・・

スクリーンショット 2020-12-12 3.40.55.pngスクリーンショット 2020-12-12 3.41.10.pngスクリーンショット 2020-12-12 3.41.18.png

まとめ

  • CreateReactAppに新しく入ったWebVitalの計測機能はweb-vitalsライブラリのセットアップを事前にしてくれているというものでした
  • 取得できるメトリクスを収集するのは簡単なのでそれをどう活用していくか考えていけばよさそうですね
43
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
21