nytimes / react-tracking

🎯 Declarative tracking for React apps.
https://open.nytimes.com/introducing-react-tracking-declarative-tracking-for-react-apps-2c76706bb79a
Other
1.87k stars 123 forks source link

Options.process with useTracking not running as expected. #189

Open jviray-aswf opened 2 years ago

jviray-aswf commented 2 years ago

When using the useTracking Hook with an options.process set, it only seems to execute on initial page load. When switching between pages, the process function does not execute.

Example: https://codesandbox.io/s/keen-sutherland-dqt20

bgergen commented 2 years ago

This actually is the expected behavior—the process function only fires on initial page load. The example pageview event in the docs doesn't really account for a single-page app; it fires in the componentDidMount phase of it's component's lifecycle, which only runs once. In your example, even though the "page" is changing via soft routing, the process function only runs when the App component initially mounts.

That said, I wonder if the process function, since we intentionally set it only once in a top-level component, should take SPAs and soft routing into account, maybe as an opt-in behavior. @tizmagik What do you think?

tizmagik commented 2 years ago

Thanks for the example code and opening an issue @jviray-aswf -- and thanks for taking a look @bgergen !

So after thinking about this for a bit, I think I would consider this a bug -- or at least a caveat worth documenting.

If you include a useEffect hook in TrackablePage you can see that it does mount and unmount, but react-tracking has an optimization in place to memoize and avoid re-renders. It's possible we need an extra useEffect call under the hood to handle this specific dispatchOnMount behavior?

Here's an updated example with the useEffect hook logging mount/unmounts plus a workaround (calling trackEvent directly): https://codesandbox.io/s/flamboyant-keldysh-g3xt9?file=/src/App.tsx

I'm not sure what the fix would be necessarily, or if this is something we should just document somehow? Any thoughts?

bgergen commented 2 years ago

Just submitted a PR to add a note to the docs: https://github.com/nytimes/react-tracking/pull/192. I do think we should address this. It will probably involve breaking up this useEffect block into two to differentiate the behavior based on whether options.process exists. I can play around with it a bit and see what makes sense.