Track Hubspot Events in a React SPA
Learn how to use Hubspot to track user activity when using client side routing in React.
Published: 20 Mar, 2024
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
.
import { useEffect, useMemo } from "react";
import { useLocation } from "react-router-dom";
import useGetCustomer from "./hooks/useGetCustomer";
export default function useHubSpot() {
const { customer } = useGetCustomer();
// eslint-disable-next-line no-underscore-dangle
const hubspot = useMemo(
() => (typeof window !== "undefined" && window._hsq ? window._hsq : []),
[]
);
const { pathname } = useLocation();
useEffect(() => {
if (hubspot && pathname) {
hubspot.push(["setPath", pathname]);
hubspot.push(["trackPageView"]);
if (customer) {
hubspot.push(["identify", { email: customer.email }]);
}
}
}, [pathname, hubspot, customer]);
}
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.
import useHubspot from "./hooks/useHubspot";
export default function MainLayout() {
useHubspot();
}
<BrowserRouter>
<Route path="/" element={<MainLayout />}>
<Route path="my-page" element={<MyPage />} />
</Route>
</BrowserRouter>
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.