Google Analytics 4 in React

for web developers

Vergil
3 min readJul 6, 2022

Intro

Google Analytics 4 is here and it’s going to replace Universal Analytics. Universal Analytics will stop tracking on July 1, 2023.

ReactJs

Migration

Until now you might have used react-ga library which uses Universal Analytics. Authors of this library did not confirm the upgrade for GA4 but don’t worry. There’s already replacement library called react-ga4.

Implementation

There’s a lot of tutorials how to create property and stream, so I’ll skip that and go to the important stuff.

We will take attention to Measurement ID and Enhanced measurement setting.

Initialize

add ReactGa.initialize() in your main index file

Enhanced measurement

Then you need to track pageViews, right? So you do what library’s documentation tells you, something like:

don’t do this

Wrong! Do you remember Enhanced measurement setting from 1st image? GA4 is intelligent enough to measure all of those interactions automatically. You don’t have to bother to code them in your project.

enhanced measurements

“But React is SPA and does not reload the page” — yeah, and GA4 can deal with that. I tested this, you can trust me. So what has left to do?

Events

Anything extra for your use-case, you have to code by yourself. That’s basically unchanged from UA, so let’s recap. Except automatic events and enhanced measurement events, you can also have:

For recommended events use its name as first argument and params object as second. That param is predefined type which can be found by clicking on desired event from this list. For example, login’s params has just a single property method.

For custom events you just pass options object. All supported fields are here but I also recommend you to read this documentation. Just Category and Action are required, but Label is really useful.

I also put my events in separate file and just import them where I need them.

GA events
import Load objects button event
import Login via Salesforce event

From developers perspective that’s basically all you need. Just initialize your GA4 and track recommended and custom events.

Questions? Tips? Let me know in comments 🙃

--

--

Vergil

I just love modern programming languages, don’t you?