Track Hubspot Events in a React SPA
Learn how to use Hubspot to track user activity when using client side routing in React.
Tracking user activity in traditional server rendered pages is simple. You add the Hubspot tracking code to the <head>
element, and it will automatically track page visits because pages are rendered every time the user clicks a link.
In React, you'll be using libraries like React Router to provide navigation on the client instead. Meaning, pages will be rendered without the browser doing anything. The Hubspot tracking code will fire only once, and will be unable to track subsequent pages that the user navigates to.
To solve the problem, you'll use a React hook.
First, get the tracking code from Hubspot and add it to your index.html
page like so:
<script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/45374325.js"></script>
Next, create a file called useHubspot.js
. This will contain a custom hook called useHubspot
.
Here, I'm also using a hook called useGetCustomer
that will fetch customer information from my server. Then, I'm sending the customer's email address to Hubspot for tracking.
You can add this hook to specific pages you want to track or, add it to your app's main layout to track all pages.
Now page visits will be tracked in Hubspot.
You can also track any custom events right in this hook if needed.
If you liked this post, please consider subscribing to my newsletter to receive notifications about new ones like it.