> ## Documentation Index
> Fetch the complete documentation index at: https://bhavishaya.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# React.js

> Add Analytiq to your React app in one file. Works with Vite and Create React App.

<Note>
  **Before starting:** Get your API key from the [Settings page](/api-key)
</Note>

## What you'll need

* React app (Vite or Create React App)
* Your Analytiq API key
* An existing auth state (like `useAuth()`, a `useState`, or a Context)

***

## Step 1 — Install the SDK

```bash theme={null}
npm install analytiq
```

***

## Step 2 — Create `src/analytics.jsx` (One-time setup)

Create a new file in your `src/` folder called `analytics.jsx`. This is the **only place** Analytiq is configured. You never touch it again after this.

<Tabs>
  <Tab title="JavaScript (analytics.jsx)">
    ```jsx src/analytics.jsx theme={null}
    import { Analytiq, identify, reset, track } from 'analytiq/react'
    import { useEffect } from 'react'

    // Import YOUR app's authentication hook here
    import { useAuth } from './context/AuthContext'

    export function AnalyticsProvider({ children }) {
      const { user } = useAuth()

      // Bridges your Auth system to the Analytics SDK
      useEffect(() => {
        if (user) {
          identify(user)
        } else {
          reset()
        }
      }, [user])

      return (
        <>
          <Analytiq apiKey={import.meta.env.VITE_ANALYTIQ_KEY} />
          {children}
        </>
      )
    }

    // Re-export so other files import from here, not from the package directly
    export { track }
    ```
  </Tab>

  <Tab title="TypeScript (analytics.tsx)">
    ```tsx src/analytics.tsx theme={null}
    import { Analytiq, identify, reset, track } from 'analytiq/react'
    import { useEffect } from 'react'
    import { useAuth } from './context/AuthContext'

    export function AnalyticsProvider({ children }: { children: React.ReactNode }) {
      const { user } = useAuth()

      useEffect(() => {
        if (user) {
          identify(user)
        } else {
          reset()
        }
      }, [user])

      return (
        <>
          <Analytiq apiKey={import.meta.env.VITE_ANALYTIQ_KEY as string} />
          {children}
        </>
      )
    }

    export { track }
    ```
  </Tab>
</Tabs>

**Add your API key to `.env`:**

```bash theme={null}
VITE_ANALYTIQ_KEY=pk_live_your_actual_key_here
```

***

## Step 3 — Wrap your app with AnalyticsProvider

Open `src/App.jsx` (or `App.tsx`) and wrap your existing app with the provider you just created. Make sure it goes **inside** your Auth provider.

```jsx src/App.jsx theme={null}
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { AuthProvider } from './context/AuthContext'
import { AnalyticsProvider } from './analytics.jsx'  // Import your new file

function App() {
  return (
    <AuthProvider>
      <AnalyticsProvider>      {/* Wrap your app here */}
        <BrowserRouter>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/dashboard" element={<Dashboard />} />
          </Routes>
        </BrowserRouter>
      </AnalyticsProvider>
    </AuthProvider>
  )
}

export default App
```

<Check>
  That's the entire setup! You never touch these files again for analytics purposes.
</Check>

***

## What the setup handles automatically

| Action                             | What happens                                                         |
| ---------------------------------- | -------------------------------------------------------------------- |
| App loads (user logged out)        | `init()` runs once, anonymous tracking begins                        |
| App loads (user already logged in) | `userId` restored from `localStorage`, user identified immediately   |
| User logs in (your auth changes)   | `useEffect` detects new user → `identify(user)` called automatically |
| User logs out (your auth clears)   | `user` becomes `null` → `reset()` called automatically               |
| User goes offline                  | Events saved to `localStorage`, retried on reconnect                 |

***

## Step 4 — Track Custom Events

For any specific action you want to measure (page views, clicks, purchases), import `track()` **from your `analytics.jsx` file** and call it where the action happens.

<Tabs>
  <Tab title="Track a page view">
    ```jsx src/pages/Home.jsx theme={null}
    import { useEffect } from 'react'
    import { track } from '../analytics.jsx'   // Import from your hub, not the package!

    export function Home() {
      useEffect(() => {
        track('Home_page_view')
      }, [])

      return <h1>Welcome!</h1>
    }
    ```
  </Tab>

  <Tab title="Button click">
    ```jsx src/components/PricingCard.jsx theme={null}
    import { track } from '../analytics.jsx'

    function PricingCard({ plan }) {
      const handleUpgrade = () => {
        track('upgrade_clicked', { plan: plan.name, price: plan.price })
        // your existing upgrade logic...
      }

      return <button onClick={handleUpgrade}>Upgrade to {plan.name}</button>
    }
    ```
  </Tab>

  <Tab title="After an API call succeeds">
    ```jsx src/pages/Checkout.jsx theme={null}
    import { track } from '../analytics.jsx'

    async function handlePayment(paymentData) {
      const result = await processPayment(paymentData)

      if (result.success) {
        track('order_completed', {
          order_id: result.orderId,
          total: result.total,
        })
      } else {
        track('payment_failed', { reason: result.errorCode })
      }
    }
    ```
  </Tab>
</Tabs>

<Note>
  **Rule of thumb:** Always import `track` from your local `analytics.jsx` file, not directly from `analytiq`. This ensures your tracking is always correctly initialized before it fires.
</Note>

***

## Step 5 — Verify it's working

1. Run your app: `npm run dev`
2. Log into your app (so your `useAuth` returns a user)
3. Open browser DevTools (`F12`) → **Network** tab, filter by `track`
4. You should see a `POST /api/events/track` request for every event you fire

***

## Common Mistakes

| Mistake                                                      | Symptom                                | Fix                                                                 |
| ------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------------- |
| Using `ANALYTIQ_KEY` without `VITE_` prefix                  | `undefined` key error in console       | Rename to `VITE_ANALYTIQ_KEY` in `.env`                             |
| Importing `track` from `analytiq` instead of `analytics.jsx` | Events fire before SDK initializes     | Always import from your local `analytics.jsx` hub                   |
| `AnalyticsProvider` placed outside `AuthProvider`            | `useAuth()` crashes with context error | Ensure Auth wraps Analytics in `App.jsx`                            |
| Not calling `identify()` after login                         | Active Users shows 0 on dashboard      | The `analytics.jsx` `useEffect` must receive a truthy `user` object |
