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

# API Reference

> Complete API documentation for the React SDK

# React SDK API Reference

Complete reference for all exports, types, and interfaces in `@superflag-sh/react`.

## Components

### SuperflagProvider

Context provider that wraps your app and manages flag state.

```tsx theme={null}
<SuperflagProvider clientKey="pub_..." ttlSeconds={60}>
  <App />
</SuperflagProvider>
```

**Props:**

| Prop         | Type             | Required | Default        | Description                 |
| ------------ | ---------------- | -------- | -------------- | --------------------------- |
| `clientKey`  | `string`         | No       | env var        | Public client key (`pub_*`) |
| `ttlSeconds` | `number`         | No       | `60`           | Cache TTL in seconds        |
| `storage`    | `StorageAdapter` | No       | `localStorage` | Custom storage adapter      |
| `children`   | `ReactNode`      | Yes      | -              | React children              |

**Environment Variable Fallback:**

If `clientKey` is not provided, the provider looks for:

* `process.env.NEXT_PUBLIC_SUPERFLAG_CLIENT_KEY` (Next.js)
* `import.meta.env.VITE_SUPERFLAG_CLIENT_KEY` (Vite)
* `process.env.REACT_APP_SUPERFLAG_CLIENT_KEY` (CRA)

## Hooks

### useFlag

Get the value of a feature flag with type safety.

```tsx theme={null}
const value = useFlag<T>(name: string, fallback?: T): T | undefined
```

**Parameters:**

| Parameter  | Type     | Required | Description                     |
| ---------- | -------- | -------- | ------------------------------- |
| `name`     | `string` | Yes      | Flag key name                   |
| `fallback` | `T`      | No       | Default value if flag not found |

**Returns:**

The flag value cast to type `T`, or `fallback` if provided, or `undefined`.

**Examples:**

```tsx theme={null}
// Boolean flag
const enabled = useFlag('feature-enabled', false)

// String flag
const theme = useFlag<string>('theme', 'light')

// Number flag
const limit = useFlag<number>('rate-limit', 100)

// JSON flag
const config = useFlag<{ api: string }>('api-config', { api: '/v1' })
```

### useFlags

Get the current SDK state.

```tsx theme={null}
const state = useFlags(): SuperflagState
```

**Returns:**

| Field           | Type              | Description                          |
| --------------- | ----------------- | ------------------------------------ |
| `flags`         | `Flags`           | All flags as key-value pairs         |
| `status`        | `SuperflagStatus` | Current SDK status                   |
| `ready`         | `boolean`         | Shorthand for `status === 'ready'`   |
| `loading`       | `boolean`         | Shorthand for `status === 'loading'` |
| `version`       | `number \| null`  | Config version number                |
| `etag`          | `string \| null`  | ETag from last fetch                 |
| `lastFetchedAt` | `number \| null`  | Timestamp of last fetch              |
| `error`         | `string \| null`  | Error message if failed              |

**Example:**

```tsx theme={null}
function MyComponent() {
  const { ready, loading, error, flags } = useFlags()

  if (loading) return <Spinner />
  if (error) return <Error message={error} />
  if (!ready) return null

  return <div>Loaded {Object.keys(flags).length} flags</div>
}
```

## Types

### SuperflagStatus

```tsx theme={null}
type SuperflagStatus = "idle" | "loading" | "ready" | "error" | "rate-limited"
```

| Status         | Description                   |
| -------------- | ----------------------------- |
| `idle`         | Initial state before fetching |
| `loading`      | Fetching flags from API       |
| `ready`        | Flags loaded successfully     |
| `error`        | Failed to load flags          |
| `rate-limited` | Monthly quota exceeded        |

### SuperflagState

```tsx theme={null}
interface SuperflagState {
  flags: Flags
  status: SuperflagStatus
  version: number | null
  etag: string | null
  lastFetchedAt: number | null
  error: string | null
}
```

### Flags

```tsx theme={null}
type Flags = Record<string, FlagValue>

interface FlagValue {
  type: "bool" | "string" | "number" | "json"
  value: boolean | string | number | object
}
```

### StorageAdapter

Custom storage adapter interface for persisting flags.

```tsx theme={null}
interface StorageAdapter {
  getItem(key: string): Promise<string | null>
  setItem(key: string, value: string): Promise<void>
  removeItem(key: string): Promise<void>
}
```

**Example Implementation:**

```tsx theme={null}
const sessionStorageAdapter: StorageAdapter = {
  async getItem(key) {
    return sessionStorage.getItem(key)
  },
  async setItem(key, value) {
    sessionStorage.setItem(key, value)
  },
  async removeItem(key) {
    sessionStorage.removeItem(key)
  }
}
```

### SuperflagProviderProps

```tsx theme={null}
interface SuperflagProviderProps {
  clientKey?: string
  ttlSeconds?: number
  storage?: StorageAdapter
  children: React.ReactNode
}
```

## Constants

### Cache Key

The SDK stores cached config under this localStorage key:

```tsx theme={null}
const CACHE_KEY = "superflag:cache:v1"
```

## Exports

All exports from `@superflag-sh/react`:

```tsx theme={null}
// Components
export { SuperflagProvider }

// Hooks
export { useFlag, useFlags }

// Types
export type {
  SuperflagStatus,
  SuperflagState,
  SuperflagProviderProps,
  StorageAdapter,
  Flags,
  FlagValue,
  FlagType
}
```

## TypeScript Usage

The SDK is fully typed. Import types alongside runtime exports:

```tsx theme={null}
import {
  SuperflagProvider,
  useFlag,
  useFlags,
  type SuperflagState,
  type StorageAdapter
} from '@superflag-sh/react'
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Usage Guide" icon="code" href="/react/usage">
    Learn how to use the SDK
  </Card>

  <Card title="Examples" icon="lightbulb" href="/react/examples">
    Common patterns and recipes
  </Card>
</CardGroup>
