React
Provider, hook, exposure event and admin menu of the React integration.
The React integration consists of a provider component and a hook. They handle variant fetching, caching, loading states and exposure callbacks. Import them from the react submodule:
import { LeveredProvider, useVariant } from '@levered_dev/sdk/react';LeveredProvider
Wrap the application, or the subtree that needs variants, in LeveredProvider. The provider creates one LeveredClient instance, which all useVariant calls below it use.
import { LeveredProvider } from '@levered_dev/sdk/react';
function App() {
return (
<LeveredProvider
apiUrl="https://api.levered.dev"
anonymousId={getOrCreateSessionId()}
onExposure={(event) => {
// Log to your warehouse (BigQuery, Snowflake, Segment, etc.)
analytics.track('levered_exposure', event);
}}
>
<YourApp />
</LeveredProvider>
);
}Props
| Prop | Type | Required | Description |
|---|---|---|---|
apiUrl | string | Yes | Base URL of the Levered API, for example https://api.levered.dev. |
anonymousId | string | Yes | Stable anonymous identifier of the current user or session. It must match the anonymous_id column of the exposure table in the warehouse. |
onExposure | (event: ExposureEvent) => void | No | Called when the SDK fetches a variant for a user from the API. A repeat request that is answered from the in-memory cache (60 seconds) does not call it again. Log the exposure event to the warehouse in this callback. |
Generate a persistent identifier for anonymousId and store it, for example in a cookie or in local storage. Levered uses the identifier to match the rewards of a user to the variant that the user was assigned.
useVariant
useVariant fetches a variant for an optimization. The hook returns variant values on the first render. While the request is loading, these are the fallback values.
import { useVariant } from '@levered_dev/sdk/react';
function HeroSection() {
const { variant, isLoading } = useVariant({
optimizationId: 'abc-123',
fallback: { headline: 'Welcome', cta_text: 'Get Started' },
context: { device: 'mobile' },
});
return (
<section>
<h1>{variant.headline}</h1>
<button>{variant.cta_text}</button>
</section>
);
}Options
| Option | Type | Required | Description |
|---|---|---|---|
optimizationId | string | Yes | UUID of the optimization to serve variants from. |
fallback | T | Yes | Default variant values that the hook returns while loading and on error. It also defines the TypeScript type of the variant object. |
context | Record<string, unknown> | No | Context values for the context factors of the optimization, for example { device: 'mobile', country: 'US' }. |
Return value
| Field | Type | Description |
|---|---|---|
variant | T | The resolved variant values. The value is fallback until the first request succeeds. If the API returns no variant, the value becomes {} and keeps none of the fallback fields. If a later re-fetch fails, the hook keeps the last resolved value. |
isLoading | boolean | true while a fetch is in flight. This applies to the first fetch and to every re-fetch. |
Type safety
The fallback option defines the type of the variant object. TypeScript infers the type from the fallback, so variant.headline and variant.cta_text are typed.
// TypeScript knows variant has { headline: string; cta_text: string }
const { variant } = useVariant({
optimizationId: 'abc-123',
fallback: { headline: 'Welcome', cta_text: 'Get Started' },
});Re-fetching
The hook re-fetches when optimizationId, anonymousId (from the provider) or context changes.
ExposureEvent
When the SDK fetches a variant for a user, it calls the onExposure callback with this event:
interface ExposureEvent {
/** The user's anonymous identifier. */
anonymousId: string;
/** UUID of the optimization that served this variant. */
optimizationId: string;
/** Display name of the optimization. */
optimizationName?: string;
/** The design-factor values of the assigned variant. */
variant: Record<string, string | number | boolean>;
/** Context attributes sent with the request. */
context: Record<string, unknown>;
/** ISO-8601 timestamp of the exposure. */
timestamp: string;
/** Whether the request was routed to the holdout instead of the optimization. */
isHoldout: boolean;
/** Whether the model had enough data to route (true) or fell back to random sampling (false). */
trained: boolean;
}Forward this event to the data warehouse. Levered reads the exposure data from the warehouse to train the model. If exposures are not logged, the model cannot be trained.
LeveredAdminMenu
LeveredAdminMenu is a debug overlay for overriding the variant assignment during development. It renders a floating Levered button at the bottom right. The button opens a drawer at the right edge, labelled Variant Preview, in which a value can be selected for each design factor.
import { LeveredAdminMenu } from '@levered_dev/sdk/react';
function App() {
const { variant, isLoading } = useVariant({
optimizationId: 'abc-123',
fallback: { headline: 'Welcome', cta_text: 'Get Started' },
});
const [override, setOverride] = useState<Record<string, string | number | boolean> | null>(null);
const activeVariant = override ?? variant;
return (
<>
<HeroSection variant={activeVariant} />
<LeveredAdminMenu
enabled={process.env.NODE_ENV === 'development'}
variants={[
{
name: 'headline',
label: 'Headline',
options: [
{ value: 'Welcome', label: 'Welcome' },
{ value: 'Hello there', label: 'Hello there' },
{ value: 'Try it free', label: 'Try it free' },
],
},
{
name: 'cta_text',
label: 'CTA Text',
options: [
{ value: 'Get Started', label: 'Get Started' },
{ value: 'Sign Up Now', label: 'Sign Up Now' },
],
},
]}
currentValues={activeVariant}
onOverride={(values) => setOverride(values)}
onReset={() => setOverride(null)}
/>
</>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Whether to render the preview drawer. |
variants | AdminVariantConfig[] | None | Array of design factors with their possible values. |
width | number | 272 | Drawer width in px. |
currentValues | Record<string, string | number | boolean> | None | The currently active variant values. |
onOverride | (values: Record<string, string | number | boolean>) => void | None | Called when the user selects a variant override. |
baseline | Record<string, string | number | boolean> | None | Reference values, usually the fallback. If set, a Reset to Baseline button calls onOverride(baseline). |
onReset | () => void | None | Called when the user clicks Reset to Live. Ignored if baseline is set. If neither baseline nor onReset is set, the reset button is hidden. |
AdminVariantConfig
Each entry in the variants array describes one design factor:
interface AdminVariantConfig {
/** Property name (e.g. "headline"). */
name: string;
/** Display label in the UI (defaults to name). */
label?: string;
/** Possible values to switch between. */
options: Array<{
value: string | number | boolean;
label?: string;
}>;
}Enable the admin menu in development and staging environments only. It is a debugging tool, and end users should not see it.
Full example
The following example combines the provider, the hook, exposure logging and the admin menu:
import { useState } from 'react';
import { LeveredProvider, useVariant, LeveredAdminMenu } from '@levered_dev/sdk/react';
function App() {
return (
<LeveredProvider
apiUrl="https://api.levered.dev"
anonymousId={getOrCreateSessionId()}
onExposure={(event) => {
analytics.track('levered_exposure', event);
}}
>
<HeroPage />
</LeveredProvider>
);
}
function HeroPage() {
const { variant, isLoading } = useVariant({
optimizationId: 'abc-123',
fallback: { headline: 'Welcome', cta_text: 'Get Started' },
});
const [override, setOverride] = useState<Record<string, string | number | boolean> | null>(null);
const active = override ?? variant;
return (
<main>
<h1>{active.headline}</h1>
<button>{active.cta_text}</button>
<LeveredAdminMenu
enabled={process.env.NODE_ENV === 'development'}
variants={[
{
name: 'headline',
options: [
{ value: 'Welcome' },
{ value: 'Hello there' },
{ value: 'Try it free' },
],
},
{
name: 'cta_text',
options: [
{ value: 'Get Started' },
{ value: 'Sign Up Now' },
],
},
]}
currentValues={active}
onOverride={setOverride}
onReset={() => setOverride(null)}
/>
</main>
);
}