> For the complete documentation index, see [llms.txt](https://docs.millimetric.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.millimetric.ai/sdks/frameworks/react.md).

# React

React (Vite, CRA, Remix client) + @millimetric/track.

## Install

```bash
npm i @millimetric/track
```

## Init at the root

```tsx
// src/main.tsx (Vite)
import { StrictMode, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { init } from "@millimetric/track";
import App from "./App";

function Analytics({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    init({
      key: import.meta.env.VITE_AOA_KEY!,
      host: import.meta.env.VITE_AOA_HOST ?? "https://api.millimetric.ai"
    });
  }, []);
  return <>{children}</>;
}

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <Analytics>
      <App />
    </Analytics>
  </StrictMode>
);
```

The SDK auto-fires `$pageview` on init *and* on every `history.pushState` / `popstate`, so React Router and Tanstack Router are handled without extra wiring.

## Identify on login

```tsx
import { useEffect } from "react";
import { identify } from "@millimetric/track";
import { useUser } from "./auth";

export function IdentifyOnAuth() {
  const user = useUser();
  useEffect(() => {
    if (user) identify(user.id, { email: user.email, plan: user.plan });
  }, [user?.id]);
  return null;
}
```

Drop `<IdentifyOnAuth />` once near the top of your tree — usually next to your auth provider.

## Track on intent

```tsx
import { track } from "@millimetric/track";

export function PricingCard({ plan }: { plan: "free" | "pro" }) {
  return (
    <button onClick={() => track("clicked_pricing", { plan })}>
      Choose {plan}
    </button>
  );
}
```

## A tiny custom hook (optional)

```tsx
import { useCallback } from "react";
import { track } from "@millimetric/track";

export function useTrack() {
  return useCallback(
    (event: string, properties?: Record<string, unknown>) => track(event, properties),
    []
  );
}
```

It's a one-liner — no global provider needed. The SDK is its own singleton.

## React Router — manual page() if you turn off auto

Auto-pageviews handle most apps. Turn them off only if you need full control:

```tsx
init({ key, autoPageView: false });
```

```tsx
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { page } from "@millimetric/track";

export function ManualPageviews() {
  const location = useLocation();
  useEffect(() => {
    page(location.pathname);
  }, [location.pathname]);
  return null;
}
```

## React Server Components / SSR

Don't call SDK functions in components rendered on the server — the SDK reads `localStorage` and `navigator`. Mark anything analytics-related `"use client"` (Next.js / RSC) or render it inside a client-only boundary (Remix `ClientOnly`).

For Next.js specifically, see the [Next.js page](https://docs.millimetric.ai/sdks/frameworks/nextjs.md).

## Tracking errors / boundaries

```tsx
import { Component } from "react";
import { track } from "@millimetric/track";

export class TrackingErrorBoundary extends Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  state = { hasError: false };

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    track("ui_error", {
      message: error.message,
      component_stack: info.componentStack?.slice(0, 1000)
    });
  }

  render() {
    return this.state.hasError ? <p>Something went wrong.</p> : this.props.children;
  }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.millimetric.ai/sdks/frameworks/react.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
