[QUESTION] Best practices for using react-ga4
Closed this issue · 6 comments
Instead of copying and pasting a custom event, I have created a utils/ga.js
file which is the below. I am just wondering if this would still be ok to use like this?
import ReactGA from 'react-ga4'
// initialize google analytics
ReactGA.initialize('G-7XXX')
// custom pageview with the location from react router
export const pageView = path => {
return ReactGA.send({hitType: 'pageview', page: path})
}
// custom event with label being an optional parameter
export const customEvent = (category, action, label = '') => {
return ReactGA.event({
category: category,
action: action,
label: label,
})
}
The use of useLocation here, will this still work? For example if I want to import the function like so:
import {pageView} from '../utils/ga.js'
import {useLocation} from 'react-router-dom'
// and use it like
let location = useLocation()
pageView(location.pathname)
Would the useLocation hook know the location even though I called it in a different file?
Also is this a good practice, especially with using the customEvent and calling it like
import {customEvent} from '../utils/ga.js'
const event = customEvent
event('somestring', 'some_event')
@mrpbennett Do you know how to properly use dimensions?
@richardnikolas in all honesty not really...but i have implemented it like above, and seems to be working well capturing my custom events
@mrpbennett I see... apparently there is no way to set dimensions, so this lib will not work for me. But thanks tho!
@mrpbennett if you have a ReactGA.event or ReactGA.send call in a react component, does it actually get sent multiple times when that component re-renders?
@mrpbennett I see... apparently there is no way to set dimensions, so this lib will not work for me. But thanks tho!
Not sure what you mean? You can send custom parameters to the ReactGA.send
function. Whether they are dimensions or metrics is decided on the Google Analytics configuration options on the UI.
@mrpbennett if you have a ReactGA.event or ReactGA.send call in a react component, does it actually get sent multiple times when that component re-renders?
You should be firing this kind of thing inside useEffect
, otherwise yes it will fire every time the component renders.