React
@stancelens/react: a provider, hooks for tracking and feature flags, and page views for any router.
React bindings for the JavaScript SDK. React 18 and 19, server rendering included.
Install from source
Neither package is on npm yet. Build tarballs of both from the Stancelens repository, then install them in your app:
bash
cd stancelens/packages/js && bun install && bun run build && bun pm pack
cd ../react && bun install && bun run build && bun pm pack
# in your app
npm install /path/to/stancelens/packages/js/stancelens-js-0.1.0.tgz \
/path/to/stancelens/packages/react/stancelens-react-0.1.0.tgzQuick start
tsx
import { StancelensProvider, useStancelens, useFlag } from "@stancelens/react";
<StancelensProvider options={{ site: "SITE_ID", autoPageviews: true }}>
<App />
</StancelensProvider>;
function Checkout() {
const stancelens = useStancelens();
const { value, loading } = useFlag("new-checkout");
if (loading) return <Spinner />;
return (
<button onClick={() => stancelens.track("checkout_started")}>
{value === "v2" ? "Pay now" : "Checkout"}
</button>
);
}With a router
Use <TrackPageviews> instead of autoPageviews when page views should follow your router's location. With react-router:
tsx
import { useLocation } from "react-router";
import { TrackPageviews } from "@stancelens/react";
function Analytics() {
return <TrackPageviews location={useLocation()} />;
}API
| Export | What it does |
|---|---|
<StancelensProvider options={…}> | Initialises the shared client from @stancelens/js (init(options), read once on first render), so track() imported from @stancelens/js reaches the same client. |
<StancelensProvider client={…}> | Provides a client you made with createClient(). |
useStancelens() | The client from the nearest provider, else the shared client. With neither, a disabled client that sends nothing (with a console warning in browsers). |
useFlag(key) | { value, enabled, loading }. value is false while loading, when off and on error; enabled is value !== false. Records one $exposure per value once loaded, false included; unknown keys record nothing. |
<TrackPageviews location props?> | Sends a page view whenever location changes. location is a path string or { pathname, search?, hash? }. Don't combine with autoPageviews: true. |
Behaviour
- Server rendering sends nothing. On the server the provider holds a disabled client and
useFlagrenders{ loading: true }, so the first client render matches the server HTML. - No flash for known flags. After mount,
useFlagshows the last known value (from storage oroptions.flags) at once, then the fetched one. It updates afteridentify()orreset(). - Many
useFlagcalls share one flags request. - One page view per location, also under
<StrictMode>. - Hooks never throw during render. The provider throws only when
options.siteis missing.