Skip to Content
Docshook

hook

A custom React hook returned as the second array item from createTracker.
It provides access to tracking functionality and context management within your components.

import { createTracker } from "@offlegacy/event-tracker"; const [Track, useTracker] = createTracker({...}) function MyComponent() { const { setContext, getContext, track, trackWithSchema } = useTracker(); return ( // Your component content ); }

Return Value

The hook returns an object with the following properties:

setContext

  • Type: (context: Context) => void
  • Sets or updates the current tracking context
  • Can be used to update user information, session data, etc.
const { setContext } = useTracker(); // Set new context setContext({ userId: "user-123" }); // Update context based on previous value setContext((prev) => ({ ...prev, lastActive: new Date(), }));

getContext

  • Type: () => Context
  • Returns the current tracking context
  • Useful for accessing current tracking state
const { getContext } = useTracker(); const currentContext = getContext(); console.log("Current user:", currentContext.userId);

track

  • Type: Record<keyof EventNames, (params: EventParams, options?: TrackingOptions) => void>
  • Object containing all configured event tracking functions
  • Keys match the event names defined in your tracker configuration
  • Accepts optional TrackingOptions for advanced control
const { track } = useTracker(); // Track a simple click event track.onClick({ buttonId: "submit" }); // Track with conditional logic track.onClick( { buttonId: "premium" }, { enabled: (context) => context.user?.isPremium, }, ); // Track with debouncing track.onClick( { buttonId: "search" }, { debounce: { delay: 300, leading: false, trailing: true }, }, ); // Track with throttling track.onClick( { buttonId: "rapid-action" }, { throttle: { delay: 1000, leading: true, trailing: false }, }, ); // Track an impression track.onImpression({ elementId: "hero" });

trackWithSchema

  • Type: Record<keyof Schemas, (params: SchemaParams, options?: TrackingOptions) => void>
  • Object containing all configured event tracking functions with schema validation
  • Keys match the event names defined in your tracker configuration
  • Accepts optional TrackingOptions for advanced control
const { trackWithSchema } = useTracker(); // Track a click event with schema trackWithSchema.onClick({ schema: "click", params: { buttonId: "submit" } }); // Track with conditional logic and schema trackWithSchema.onClick( { schema: "premium_click", params: { buttonId: "premium", userId: "123" }, }, { enabled: (context, params) => context.user?.id === params.userId, }, ); // Track with throttling and schema trackWithSchema.onImpression( { schema: "impression", params: { elementId: "hero", userId: "123" }, }, { throttle: { delay: 2000, leading: true, trailing: false }, }, );

TrackingOptions

Both track and trackWithSchema methods accept an optional second parameter with the following options:

  • enabled?: boolean | ((context: Context, params: EventParams) => boolean) - Conditionally enable/disable event tracking
  • debounce?: DebounceConfig - Debounce configuration to prevent rapid successive events
  • throttle?: ThrottleConfig - Throttle configuration to limit event frequency

Note: debounce and throttle are mutually exclusive and cannot be used together.

DebounceConfig

interface DebounceConfig { delay: number; // Delay in milliseconds leading?: boolean; // Execute on leading edge (default: false) trailing?: boolean; // Execute on trailing edge (default: true) }

ThrottleConfig

interface ThrottleConfig { delay: number; // Delay in milliseconds leading?: boolean; // Execute on leading edge (default: true) trailing?: boolean; // Execute on trailing edge (default: false) }

Example Usage

Here’s a complete example showing how to use the custom hook:

import { createTracker } from "@offlegacy/event-tracker"; const [Track, useTracker] = createTracker({ onClick: (params) => { // Send event to analytics service analytics.track(params); }, pageView: { onPageView: (params) => { // Send event to analytics service analytics.pageView(params); }, }, }); function UserProfile({ userId }) { const { setContext, track, trackWithSchema } = useTracker(); useEffect(() => { // Update context when user ID changes setContext({ userId }); // Track page view track.onPageView({ page: "profile" }); }, [userId]); const handleSettingsClick = () => { // Track custom event trackWithSchema.onClick({ schema: "settings", params: { userId } }); }; return ( <div> <h1>User Profile</h1> <button onClick={handleSettingsClick}>Settings</button> </div> ); }

Best Practices

  1. Context Updates

    • Use setContext for global state that affects multiple events
    • Consider using the function form of setContext for updates based on previous state
  2. Event Tracking

    • Use the specific event functions from track or trackWithSchema when possible
  3. Performance

    • Avoid calling tracking functions in render
    • Use callbacks or effects for tracking
    • Consider using batching for better performance
    • Consider using data type validation for data type safety
Last updated on