react-tracker
React hook for sending events to RudderStack and Segment

This package exports a React hook which makes loading and sending events to the RudderStack, Segment or other Segment-compatible JavaScript tracking SDKs easier.
It also exports a TrackerHelper
component which renders a floating debug window, similar to the Shopify Pixel Helper, showing an expandable list of tracking events as they are received.
Installation
npm install @dangreaves/react-tracker
Loading an adapter
To send events, you must first load the appropriate JavaScript SDK for your Segment-compatible tracking service using an adapter.
Create a React component which imports your chosen adapter, and pass it to the loadAdapter
method from the useTracker
hook. Render that React component somewhere globally in your app.
In this example, we are using the RudderStack JavaScript SDK.
import { useTracker, RudderStackAdapter } from "@dangreaves/react-tracker";
function Tracker() {
const tracker = useTracker();
useEffect(() => {
tracker.loadAdapter(
new RudderStackAdapter({
writeKey: "abcdefhijklmnopqrstuvwxyq",
dataPlaneUrl: "https://foobar.dataplane.rudderstack.com",
}),
);
}, [tracker]);
return null;
}
Sending events
To send an event to the tracker, use the useTracker()
hook.
You can send events to the tracker at any time, even before the adapters have connected. The events will be buffered and sent to the adapters when ready.
import { useTracker } from "@dangreaves/react-tracker";
function Component() {
const tracker = useTracker();
return (
<button onClick={() => tracker.track("Button clicked", { foo: "bar" })}>
Click me
</button>
);
}
Rendering the helper
The TrackerHelper
component shows a floating window to debug events sent to the tracker. It shows the status of each adapter and a list of events. Each event can be expanded to show the full JSON payload which was sent to the SDK.
import { TrackerHelper } from "@dangreaves/react-tracker";
function Component() {
return <TrackerHelper />;
}
When you have rendered the component on the page, you must activate it to show it. You can do this in a few ways.
- Append
?enableTrackerHelper
to the URL and refresh the page - Set the
react-tracker-helper-enabled
local storage key to true
To close the helper, click the close button, which will set the react-tracker-helper-enabled
local storage key to false
.
If you would like to manually control the helper visibility, you can use the enabled
and onClose
props instead.
import { useState } from "react";
import { TrackerHelper } from "@dangreaves/react-tracker";
function Component() {
const [enabled, setEnabled] = useState(false);
return <TrackerHelper enabled={enabled} onClose={() => setEnabled(false)} />;
}