npm package: @plainapps/analytics-react
Description: React hooks and components for Plain Web Analytics - privacy-focused, cookie-free analytics
Author: Plain Web Analytics
Latest version: 1.0.2

# @plainapps/analytics-react

React hooks and components for [Plain Web Analytics](https://plainwebanalytics.com) - privacy-focused, cookie-free web analytics.

## Installation

```bash
npm install @plainapps/analytics-react
# or
yarn add @plainapps/analytics-react
# or
pnpm add @plainapps/analytics-react
```

## Quick Start

### 1. Add the Provider

Wrap your application with `PlainAnalyticsProvider`:

```tsx
// app/layout.tsx (Next.js App Router)
import { PlainAnalyticsProvider } from '@plainapps/analytics-react';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PlainAnalyticsProvider siteId="pwa_site_your_site_key">
          {children}
        </PlainAnalyticsProvider>
      </body>
    </html>
  );
}
```

### 2. Track Route Changes (Next.js App Router)

```tsx
// app/analytics.tsx
'use client';

import { usePageViews } from '@plainapps/analytics-react';
import { usePathname, useSearchParams } from 'next/navigation';

export function Analytics() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  usePageViews({
    deps: [pathname, searchParams.toString()],
  });

  return null;
}

// app/layout.tsx
import { Suspense } from 'react';
import { Analytics } from './analytics';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PlainAnalyticsProvider siteId="pwa_site_your_site_key">
          <Suspense fallback={null}>
            <Analytics />
          </Suspense>
          {children}
        </PlainAnalyticsProvider>
      </body>
    </html>
  );
}
```

### 3. Track Custom Events

```tsx
'use client';

import { useTrackEvent } from '@plainapps/analytics-react';

export function SignupButton() {
  const { track } = useTrackEvent();

  return (
    <button
      onClick={() => {
        track('signup_click', { source: 'homepage' });
      }}
    >
      Sign Up
    </button>
  );
}
```

## API Reference

### `PlainAnalyticsProvider`

The context provider that initializes analytics.

```tsx
<PlainAnalyticsProvider
  siteId="pwa_site_xxx"      // Required: Your site key
  apiEndpoint="..."          // Optional: Custom API endpoint
  autoPageview={true}        // Optional: Track pageview on init (default: true)
  hashMode={false}           // Optional: Track hash changes (default: false)
  debug={false}              // Optional: Log events to console (default: false)
>
  {children}
</PlainAnalyticsProvider>
```

### `usePlainAnalytics()`

Main hook to access all analytics functions.

```tsx
const {
  isInitialized,  // boolean - Whether analytics is ready
  isEnabled,      // boolean - Whether tracking is enabled
  trackPageview,  // (url?: string) => void
  trackEvent,     // (name: string, properties?: EventProperties) => void
  trackGoal,      // (goalId: string, options?: { revenue?: number; properties?: EventProperties }) => void
  setEnabled,     // (enabled: boolean) => void
  config,         // AnalyticsConfig | null
} = usePlainAnalytics();
```

### `usePageViews(options?)`

Track pageviews on route changes.

```tsx
usePageViews({
  trackOnMount: false,  // Track on initial mount (default: false)
  deps: [pathname],     // Dependencies that trigger pageview
});
```

### `useTrackEvent()`

Get a stable function for tracking events.

```tsx
const { track, isReady } = useTrackEvent();

track('event_name', { property: 'value' });
```

### `useTrackOnMount(eventName, properties?, deps?)`

Track an event when component mounts.

```tsx
useTrackOnMount('product_view', { product_id: '123' }, [productId]);
```

### `useTrackGoal()`

Get a function for tracking goal conversions.

```tsx
const trackGoal = useTrackGoal();

trackGoal('purchase', { revenue: 9900 }); // revenue in cents
```

## Framework Examples

### Next.js (App Router)

```tsx
// app/providers.tsx
'use client';

import { PlainAnalyticsProvider } from '@plainapps/analytics-react';

export function Providers({ children }) {
  return (
    <PlainAnalyticsProvider
      siteId={process.env.NEXT_PUBLIC_PLAIN_ANALYTICS_SITE_ID!}
    >
      {children}
    </PlainAnalyticsProvider>
  );
}

// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}
```

### Next.js (Pages Router)

```tsx
// pages/_app.tsx
import { PlainAnalyticsProvider, usePageViews } from '@plainapps/analytics-react';
import { useRouter } from 'next/router';

function PageViewTracker() {
  const router = useRouter();
  usePageViews({ deps: [router.asPath] });
  return null;
}

export default function App({ Component, pageProps }) {
  return (
    <PlainAnalyticsProvider siteId="pwa_site_xxx">
      <PageViewTracker />
      <Component {...pageProps} />
    </PlainAnalyticsProvider>
  );
}
```

### Create React App

```tsx
// src/index.tsx
import { PlainAnalyticsProvider } from '@plainapps/analytics-react';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <PlainAnalyticsProvider siteId="pwa_site_xxx">
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </PlainAnalyticsProvider>,
  document.getElementById('root')
);

// src/Analytics.tsx
import { usePageViews } from '@plainapps/analytics-react';
import { useLocation } from 'react-router-dom';

export function Analytics() {
  const location = useLocation();
  usePageViews({ deps: [location.pathname + location.search] });
  return null;
}
```

### Vite + React Router

```tsx
// src/main.tsx
import { PlainAnalyticsProvider } from '@plainapps/analytics-react';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';

const router = createBrowserRouter([/* routes */]);

ReactDOM.createRoot(document.getElementById('root')!).render(
  <PlainAnalyticsProvider siteId={import.meta.env.VITE_PLAIN_ANALYTICS_SITE_ID}>
    <RouterProvider router={router} />
  </PlainAnalyticsProvider>
);
```

## Privacy

Plain Web Analytics is designed with privacy in mind:

- ✅ No cookies
- ✅ No personal data collection
- ✅ GDPR, CCPA, and PECR compliant
- ✅ No consent banner required

## License

MIT