> For the complete documentation index, see [llms.txt](https://docs.tiun.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tiun.io/sdk/react-native-sdk/hooks.md).

# Hooks and events

The SDK exposes two hooks. `useTiun()` gives you the current state and the actions; `useTiunEvent()` subscribes to state changes as they happen. Both must be used inside [`<TiunProvider>`](https://docs.tiun.io/sdk/react-native-sdk/configuration.md) — they throw otherwise.

```tsx
import { useTiun, useTiunEvent } from '@tiun/react-native-sdk';

function Account() {
  const { user, isAuthenticated, login, logout } = useTiun();

  useTiunEvent('login', ({ user }) => {
    console.log('signed in as', user?.email);
  });

  // ...
}
```

***

## `useTiun()`

### State

| Property          | Type               | Description                                                                                                                                         |
| ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isAuthenticated` | `boolean`          | Whether the user has a valid session.                                                                                                               |
| `user`            | `TiunUser \| null` | The current user, or `null` when signed out.                                                                                                        |
| `ready`           | `boolean`          | Whether the snippet has initialized and is ready for commands.                                                                                      |
| `cryptoOk`        | `boolean \| null`  | Whether the WebView can use the crypto the session depends on. `null` until it reports in; `false` means authentication cannot work on this device. |

### Actions

| Method                                           | Returns                       | Description                                                                                                 |
| ------------------------------------------------ | ----------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `login()`                                        | `void`                        | Open the login overlay.                                                                                     |
| `logout()`                                       | `void`                        | Clear the session and the stored device credentials.                                                        |
| `checkout(options?)`                             | `void`                        | Open checkout. Pass `{ productId }` to buy a specific product, plus `referenceId` for a repeatable product. |
| `getUserVerificationToken()`                     | `Promise<string \| null>`     | Get a signed token for server-side verification.                                                            |
| `listProducts()`                                 | `Promise<Product[]>`          | List the products available on your snippet.                                                                |
| `getProduct(productId)`                          | `Promise<ProductDetail>`      | Get a product's details and localized pricing.                                                              |
| `listProductAccess()`                            | `Promise<ProductAccess[]>`    | List the current user's active product access.                                                              |
| `checkProductAccess(productId, { referenceId })` | `Promise<ProductAccessCheck>` | Check whether the current user has access to a product, or to one purchase of a repeatable product.         |

{% hint style="info" %}
**You don't have to wait for `ready`.** `login()`, `logout()`, and `checkout()` are queued while the snippet is starting up and run as soon as it's ready, so wiring them straight to a button is safe. The product methods wait for it the same way, and parallel calls each get their own answer. Use `ready` when you want to show a loading state instead.
{% endhint %}

### `checkout(options?)`

```tsx
const { checkout } = useTiun();

checkout({ productId: 'p-live-pro' });

// Repeatable product: tie this purchase to your own reference
checkout({ productId: 'p-live-article', referenceId: 'article-1042' });
```

`referenceId` is your own identifier for the purchase, such as an article or order ID. It's **required for repeatable products** — without it, checkout shows a configuration error — and omitted for every other product. Passing it on a product that is not repeatable shows a configuration error too. Use 1–200 characters: letters, digits, hyphens, underscores, or dots, and no spaces. Needs `@tiun/react-native-sdk` 0.4.0 or later. See [repeatable one-time purchases](https://docs.tiun.io/guides/one-time-purchases/repeatable-one-time-purchases.md).

The overlay collects the user's email, handles identity verification, takes payment, and grants access in one flow. On success the user's `productAccess` updates and `userChange` fires. For what happens behind the overlay, see [Checkout / How it works](https://docs.tiun.io/reference/checkout/how-it-works.md) in Reference.

### `getUserVerificationToken()`

Returns a signed JWT, valid for five minutes, that your backend exchanges for the verified user object. It resolves `null` when the user isn't signed in, or if tiun doesn't answer within five seconds.

```tsx
const { getUserVerificationToken } = useTiun();

async function loadProtectedData() {
  const token = await getUserVerificationToken();
  if (!token) return null;

  const response = await fetch('https://api.example.com/protected', {
    headers: { Authorization: `Bearer ${token}` },
  });

  return response.ok ? response.json() : null;
}
```

The server side is identical to the web SDK — see [verify authentication server-side](https://docs.tiun.io/guides/authentication/verify-server-side.md).

### Products

`listProducts()`, `getProduct()`, `listProductAccess()`, and `checkProductAccess()` work the same as in the web SDK and return the same types, exported from `@tiun/react-native-sdk`. They need `@tiun/react-native-sdk` 0.5.0 or later.

```tsx
const { listProducts, getProduct, listProductAccess, checkProductAccess } = useTiun();

const products = await listProducts();             // Product[]
const detail = await getProduct('p-live-pro');     // name, pricingLine, …
const access = await listProductAccess();          // [] when logged out
const { hasAccess } = await checkProductAccess('p-live-pro');

// Repeatable product: check one purchase, using the referenceId you passed to checkout()
await checkProductAccess('p-live-article', { referenceId: 'article-1042' });
```

* **Logged out is not an error.** `listProductAccess()` resolves to `[]` and `checkProductAccess()` to `{ hasAccess: false, access: null }`, the same as a signed-in user without access.
* **Failures reject** with `{ code, message, details? }`: `http_<status>` (e.g. `http_404` from `getProduct()` for an unknown product), `network_error`, `timeout` after 10 seconds, `invalid_argument` for an empty `productId`, `destroyed` when the `TiunProvider` unmounts while a call is waiting, or `unknown_error`. They don't fire the `error` event, so handle them with `try` / `catch` or `.catch()`.
* **Showing many items at once?** Call `listProductAccess()` once and look up each item in the result, rather than calling `checkProductAccess()` per item.

`user.productAccess` stays the quick way to check product IDs. Use these methods when you need a repeatable product's `referenceId`, or when a purchase started (`activatedAt`) or ends (`expiresAt`). For the full types, see [Core Methods / Products](https://docs.tiun.io/sdk/web-sdk/core-methods.md#products).

{% hint style="info" %}
**Checking on your server instead.** These methods work without a backend. If your backend serves the content, check access on the server — see [verify authentication server-side](https://docs.tiun.io/guides/authentication/verify-server-side.md).
{% endhint %}

***

## `useTiunEvent(event, handler)`

Subscribe to a tiun event. The subscription is removed automatically when the component unmounts, and the handler is always the latest one you passed — you don't need to memoize it.

```tsx
useTiunEvent('userChange', ({ isAuthenticated, user }) => {
  setUser(user);
});
```

### Event reference

| Event        | Payload                                                               | Description                                                                            |
| ------------ | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `ready`      | —                                                                     | The snippet has initialized and is ready to use.                                       |
| `userChange` | `{ event: string, isAuthenticated: boolean, user: TiunUser \| null }` | The user or their access changed — session restore, login, logout, access, or profile. |
| `login`      | `{ user: TiunUser \| null }`                                          | The user signed in.                                                                    |
| `logout`     | —                                                                     | The session was cleared.                                                               |
| `error`      | `{ code?: string, message?: string, details?: unknown }`              | An error occurred.                                                                     |

`userChange` is the event to build on: it fires on the initial session restore as well as on every later change, so a single handler keeps your UI in sync from launch onwards. **Re-check access every time it fires** — read `user.productAccess` for subscriptions and one-time products, and call `checkProductAccess(productId, { referenceId })` for a repeatable product.

Its `event` field says what changed. It's included from `@tiun/react-native-sdk` 0.5.0; before that, the payload had no `event`.

| `event`      | Meaning                                                                                                                          |
| ------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `'init'`     | First state after the snippet loads, including a restored session.                                                               |
| `'login'`    | The user signed in.                                                                                                              |
| `'logout'`   | The user signed out. `user` is `null`.                                                                                           |
| `'checkout'` | **The user's access changed** — gained or lost, for any product type. Also fires for a new reference ID of a repeatable product. |
| `'update'`   | Profile details changed, such as the email or newsletter opt-in.                                                                 |

### `error`

```tsx
useTiunEvent('error', (err) => {
  console.warn('[tiun]', err.code, err.message);
});
```

`err.code` is a string, but there is no published enum of values and codes can change between versions. Show `err.message` to users and log `err.code` for support rather than branching on specific codes.

***

## `TiunUser`

| Field                | Type       | Description                                                                                  |
| -------------------- | ---------- | -------------------------------------------------------------------------------------------- |
| `userId`             | `string`   | Stable identifier for this user in tiun.                                                     |
| `email`              | `string`   | Email on the account.                                                                        |
| `hasNewsletterOptIn` | `boolean`  | Whether the user opted in to your newsletter. Needs `@tiun/react-native-sdk` 0.4.0 or later. |
| `productAccess`      | `string[]` | Product IDs the user is entitled to.                                                         |

`productAccess` is the source of truth for what a user can access — check against it rather than tracking entitlements yourself:

```tsx
const { user } = useTiun();
const hasPro = user?.productAccess.includes('p-live-pro') ?? false;
```

For how the array is populated and when it changes, see [User object](https://docs.tiun.io/reference/authentication/user-object.md) and [Product access](https://docs.tiun.io/reference/checkout/product-access.md) in Reference.

***

For these pieces assembled into working screens, see the [React Native examples](https://docs.tiun.io/sdk/react-native-sdk/examples.md).


---

# 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.tiun.io/sdk/react-native-sdk/hooks.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.
