How to use Google Analytics with React?

To use Google Analytics with React, we run the Google Analytics code in the useEffect callback.

For instance, we write

import React, { useEffect } from "react";
import { Router, Route } from "react-router-dom";
import { createBrowserHistory } from "history";
import ReactGA from "react-ga";

ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_NO);
const browserHistory = createBrowserHistory();
browserHistory.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search);
});

const App = () => {
  useEffect(() => {
    ReactGA.pageview(window.location.pathname + window.location.search);
  }, []);

  return <div>Test</div>;
};

to call ReactGA.initialize to initialize Google Analytics.

Then we call ReactGA.pageview in the useEffect callback to record the URL the user went to when the component mounts.