Skip to content

React integration

The vantmetry/react export provides a context provider, a hook, and an error boundary for React applications.

Installation

bash
npm install vantmetry

React 18+ is a peer dependency.

Setup

Wrap your app with VantmetryProvider. This initializes the tracker once and makes the logger available to all child components via context:

tsx
import { VantmetryProvider } from 'vantmetry/react';

function App() {
  return (
    <VantmetryProvider publicKey="YOUR_PUBLIC_KEY">
      <YourApp />
    </VantmetryProvider>
  );
}

useLogger hook

Access the logger instance from any component inside the provider:

tsx
import { useLogger } from 'vantmetry/react';

function CheckoutButton() {
  const logger = useLogger();

  async function handleClick() {
    try {
      await processPayment();
    } catch (err) {
      logger.error('Payment failed', {
        step: 'checkout',
        errorCode: err.code,
      });
    }
  }

  return <button onClick={handleClick}>Pay now</button>;
}

The hook throws a descriptive error if used outside of VantmetryProvider.

Error boundary

VantmetryErrorBoundary catches React render errors and logs them automatically. Wrap it around sections of your app where you want graceful error handling:

tsx
import { VantmetryProvider, VantmetryErrorBoundary } from 'vantmetry/react';

function App() {
  return (
    <VantmetryProvider publicKey="YOUR_PUBLIC_KEY">
      <VantmetryErrorBoundary fallback={<p>Something went wrong.</p>}>
        <Dashboard />
      </VantmetryErrorBoundary>
    </VantmetryProvider>
  );
}

When a render error occurs:

  • The error and component stack are logged to Vantmetry
  • The fallback element is rendered (defaults to null if not provided)

You can nest multiple boundaries around different sections for more granular fallbacks.

Core Features

For details on batching, deduplication, circuit breaker, PII masking, and other core tracker features, see the main Tracker page.