Skip to main content

Using Bily Hooks

The useBily hook provides access to the Bily tracking client within your React components.

Basic Usage

import { useBily } from '@bilyai/react';

function TrackingComponent() {
  const bily = useBily();

  const handleClick = () => {
    bily.track('Button Clicked', {
      buttonId: 'example-button'
    });
  };

  return <button onClick={handleClick}>Track Click</button>;
}

Hook API

The useBily hook returns a tracking client with the following methods:
interface BilyClient {
  track: (event: BilyEvent, payload?: BilyPayload) => void;
  getBilyTrackingId: () => string;
  // ... other methods
}

Common Use Cases

Page View Tracking

import { useBily } from '@bilyai/react';
import { useEffect } from 'react';

function Page() {
  const bily = useBily();

  useEffect(() => {
    bily.track('Pageview', {
      pageTitle: document.title,
      sourceUrl: window.location.href
    });
  }, []);

  return <div>Page content</div>;
}

Form Submission Tracking

function ContactForm() {
  const bily = useBily();

  const handleSubmit = (e) => {
    e.preventDefault();
    
    bily.track('Form Submitted', {
      formId: 'contact-form',
      formType: 'contact'
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
    </form>
  );
}

E-commerce Tracking

function ProductCard({ product }) {
  const bily = useBily();

  const handleViewDetails = () => {
    bily.track('Product Viewed', {
      products: [{
        id: product.id,
        name: product.name,
        price: product.price,
        category: product.category
      }]
    });
  };

  return (
    <div onClick={handleViewDetails}>
      {/* Product details */}
    </div>
  );
}

Error Handling

The hook will throw an error if used outside of a BilyProvider:
function InvalidComponent() {
  // This will throw an error
  const bily = useBily();
  return null;
}
Always ensure components using useBily are wrapped with a BilyProvider.

Best Practices

  1. Use the hook at the component level that needs tracking
  2. Avoid unnecessary re-renders by memoizing callbacks
  3. Include relevant context in event payloads
  4. Handle errors appropriately

Next Steps