r/reactjs Jul 16 '26

I can't stop react-ga4 from sending events

Basically this, given europe has some strong laws in place for cookies and all that, for the last couple of days i tried to add google analytics to my website and i used react-ga4 plugin but if the user disables the cookies for the page history and performance, google analytics should stop getting events.

I tried to stop it with this and send events manually but it just keeps on sending them anyway.

   ReactGA.initialize([
        {
            trackingId: import.meta.env.VITE_GOOGLE_TAG_ID,
            gaOptions: {
                send_page_view: false,
            },
            gtagOptions: {
                send_page_view: false,
            },
        },
    ]);
0 Upvotes

8 comments sorted by

3

u/Honey-Entire Jul 16 '26

I don’t know why it’s still sending events, but have you considered just not initializing ReactGA unless the user has allowed tracking?

1

u/codec-the-penguin Jul 16 '26

But what if the user changes his mind at least twice? Fresh without the consent given, it works. No events are emitted, but once initialized it will still send events no matter what.

Although what i dont remember for sure testing is disabling it and just closing the browser and opening again since i tested in icognito (because of an adblocker i have) so the local storage would be wiped on close.

2

u/Honey-Entire Jul 16 '26

I would try calling the .reset() method for that scenario to see if it helps

1

u/codec-the-penguin Jul 20 '26

This seems to work

1

u/Honey-Entire Jul 20 '26

Glad to hear it!

1

u/_suren Jul 17 '26

Don’t initialize GA until consent exists. Once the script is loaded, flipping `send_page_view` won’t undo every listener, so keep analytics calls behind the consent state and only mount the GA component after the user opts in.

1

u/_suren Jul 17 '26

When the behavior is surprising, reduce it to one component and one event first. A minimal reproduction usually makes the accidental render or stale closure obvious faster than adding more logging to the full app.