How to set up Google Analytics for React-Router?

Keep a reference to your history object. i.e.

import { createBrowserHistory } from 'history';

var history = createBrowserHistory();

ReactDOM.render((
    <Router history={history}>
        [...]

Then add a listener to record each pageview. (This assumes you've already set up the window.ga object in the usual manner.)

history.listen((location) => {
    window.ga('set', 'page', location.pathname + location.search);
    window.ga('send', 'pageview');
});

The question is about react-ga but this package will soon be obsolete because it doesn't support Google Analytics 4. Below is a generic solution that works with any library or native gtag. For adding GA4 to React check out this answer: https://stackoverflow.com/a/73354959/2771889.

Since react-router v5.1.0 this can be solved a lot easier with useLocation.

usePageTracking.js

import { useEffect} from "react";
import { useLocation } from "react-router-dom";

const usePageTracking = () => {
  const location = useLocation();

  useEffect(() => {
    // track pageview with gtag / react-ga / react-ga4, for example:
    window.gtag("event", "page_view", {
      page_path: location.pathname + location.search,
    });
  }, [location]);
};

export default usePageTracking;

App.js

const App = () => {
  usePageTracking();

  return (...);
};

You can see this working in cra-typescript-starter where I'm using it with GA4.