# React and Next.js

> Add Lemu to a React or Next.js app with @lemuai/react: a provider, the useLemu hook and page tracking for React Router and the Next.js routers

URL: https://docs.lemuai.com/sdks/react

`@lemuai/react` adds Lemu to React and Next.js apps: a provider, a hook to send events from any component, and page tracking for React Router and both Next.js routers. It's built on [`@lemuai/analytics`](https://docs.lemuai.com/sdks/javascript) and is safe with server-side rendering: nothing touches `window` during render, and calls made on the server do nothing.

You need the write key of a **Website** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key). The source's **React / Next.js** tab under **Set up** shows the code below with your key filled in.

## Install
```bash
npm install @lemuai/react
```

## Set up

Wrap your app once with `LemuProvider`:
```tsx
import { LemuProvider } from "@lemuai/react";

export function App() {
  return (
    <LemuProvider writeKey="YOUR_WRITE_KEY">
      <Routes />
    </LemuProvider>
  );
}
```

The provider starts tracking after it mounts in the browser. It reads `options` once, when it mounts. For the options, see [Website and JavaScript](https://docs.lemuai.com/sdks/javascript#options).

## Page views

`usePageTracking(pathname)` records a page view whenever the path changes. Use it once, inside the provider.

**Next.js app router**

Put the provider in a client component:
```tsx
// app/lemu.tsx
"use client";
import { usePathname } from "next/navigation";
import { LemuProvider, usePageTracking } from "@lemuai/react";

function PageTracker() {
  usePageTracking(usePathname());
  return null;
}

export function Lemu({ children }: { children: React.ReactNode }) {
  return (
    <LemuProvider writeKey={process.env.NEXT_PUBLIC_LEMU_WRITE_KEY!}>
      <PageTracker />
      {children}
    </LemuProvider>
  );
}
```

Then use it in your root layout:
```tsx
// app/layout.tsx
import { Lemu } from "./lemu";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Lemu>{children}</Lemu>
      </body>
    </html>
  );
}
```

Set `NEXT_PUBLIC_LEMU_WRITE_KEY` to your write key. It's public, so the `NEXT_PUBLIC_` prefix is fine.

**Next.js pages router**

In `pages/_app.tsx`:
```tsx
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import { LemuProvider, usePageTracking } from "@lemuai/react";

function PageTracker() {
  usePageTracking(useRouter().asPath);
  return null;
}

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <LemuProvider writeKey={process.env.NEXT_PUBLIC_LEMU_WRITE_KEY!}>
      <PageTracker />
      <Component {...pageProps} />
    </LemuProvider>
  );
}
```

**React Router**

```tsx
import { useLocation } from "react-router-dom";
import { usePageTracking } from "@lemuai/react";

function PageTracker() {
  usePageTracking(useLocation().pathname);
  return null;
}
```

Render `<PageTracker />` inside both your router and `LemuProvider`.

## Send events

Get the client with `useLemu()` in any component:
```tsx
import { LemuEvent, useLemu } from "@lemuai/react";

function AddToCartButton({ product }) {
  const lemu = useLemu();
  return (
    <button
      onClick={() =>
        lemu.track(LemuEvent.AddToCart, {
          value: product.price,
          currency: "INR",
          content_ids: [product.sku],
        })
      }
    >
      Add to cart
    </button>
  );
}
```

`LemuEvent` has a constant for each of Meta's standard events. Any other name works as a custom event. See the [event reference](https://docs.lemuai.com/sdks/events).

`useLemu()` also works outside a provider. It returns the shared client, and calls made before the provider starts it are kept and sent once it does.

## Purchases
```tsx
const lemu = useLemu();
lemu.purchase({
  value: 1499.5,
  currency: "INR",
  order_id: order.id,
  contents: [{ id: "SKU1", quantity: 1, item_price: 1499.5 }],
});
```

`purchase` sends a `Purchase` event at once. Always pass your real order id: Lemu counts one conversion per `order_id`, however many sources report the order (this page, a webhook, a reload of the thank-you page). See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).

## Identify users
```tsx
const lemu = useLemu();

// after sign-up or login
lemu.identify(user.id, { email: user.email, phone: user.phone, first_name: user.firstName });

// on logout
lemu.reset();
```

The user id is kept and sent with every later event until `reset`. Send phone numbers in international format, for example `+919876543210`. Contact details belong in `identify` only.

## Consent and opt-out

To wait for consent, pass `requireConsent` to the provider and call `setConsent(true)` from your consent banner:
```tsx
<LemuProvider writeKey="YOUR_WRITE_KEY" options={{ requireConsent: true }}>
  <App />
</LemuProvider>

// in your consent banner
const lemu = useLemu();
lemu.setConsent(true);
```

Nothing is sent or stored until then. `lemu.optOut()` and `lemu.optIn()` turn tracking off and on, remembered in the browser. See [Consent and opt-out](https://docs.lemuai.com/sdks/javascript#consent-and-opt-out) for the details.

## Debug mode
```tsx
<LemuProvider writeKey="YOUR_WRITE_KEY" options={{ debug: true }}>
```

Every call, request and response is logged to the browser console with a `[lemu]` prefix.

## API

| Export | What it is |
|---|---|
| `LemuProvider` | Props: `writeKey`, `options` (see [options](https://docs.lemuai.com/sdks/javascript#options)), and an optional `client` from `createLemu()`. Starts tracking after mount |
| `useLemu()` | The client: `track`, `page`, `purchase`, `identify`, `reset`, `flush`, `setConsent`, `optOut`, `optIn`, `anonymousId` |
| `usePageTracking(pathname, properties?)` | Records a page view on every path change |
| `LemuEvent` | Standard event names. See the [event reference](https://docs.lemuai.com/sdks/events) |
| `createLemu()` | A separate client, for sending to a second source |
