schematic-react
schematic-react is a client-side React library for Schematic which provides hooks to track events, check flags, and more. schematic-react provides the same capabilities as schematic-js, for React apps.
Install
npm install @schematichq/schematic-react
yarn add @schematichq/schematic-react
pnpm add @schematichq/schematic-react
Usage
SchematicProvider
You can use the SchematicProvider to wrap your application and provide the Schematic instance to all components:
import { SchematicProvider } from "@schematichq/schematic-react";
ReactDOM.render(
<SchematicProvider publishableKey="your-publishable-key">
<App />
</SchematicProvider>,
document.getElementById("root"),
);
Setting context
To set the user context for events and flag checks, you can use the identify function provided by the useSchematicEvents hook:
import { useSchematicEvents } from "@schematichq/schematic-react";
const MyComponent = () => {
const { identify } = useSchematicEvents();
useEffect(() => {
identify({
keys: { id: "my-user-id" },
company: {
keys: { id: "my-company-id" },
traits: { location: "Atlanta, GA" },
},
});
}, []);
return <div>My Component</div>;
};
To learn more about identifying companies with the keys map, see key management in Schematic public docs.
Tracking usage
Once you've set the context with identify, you can track events:
import { useSchematicEvents } from "@schematichq/schematic-react";
const MyComponent = () => {
const { track } = useSchematicEvents();
useEffect(() => {
track({ event: "query" });
}, []);
return <div>My Component</div>;
};
If you want to record large numbers of the same event at once, or perhaps measure usage in terms of a unit like tokens or memory, you can optionally specify a quantity for your event:
track({ event: "query", quantity: 10 });
Checking flags
To check a flag, you can use the useSchematicFlag hook:
import { useSchematicFlag } from "@schematichq/schematic-react";
import { Feature, Fallback } from "./components";
const MyComponent = () => {
const isFeatureEnabled = useSchematicFlag("my-flag-key");
return isFeatureEnabled ? <Feature /> : <Fallback />;
};
Checking entitlements
You can check entitlements (i.e., company access to a feature) using a flag check as well, and using the useSchematicEntitlement hook you can get additional data to render various feature states:
import {
useSchematicEntitlement,
useSchematicIsPending,
} from "@schematichq/schematic-react";
import { Feature, Loader, NoAccess } from "./components";
const MyComponent = () => {
const schematicIsPending = useSchematicIsPending();
const {
featureAllocation,
featureUsage,
featureUsageExceeded,
value: isFeatureEnabled,
} = useSchematicEntitlement("my-flag-key");
if (schematicIsPending) {
return <Loader />;
}
if (featureUsageExceeded) {
return (
<div>
You have used all of your usage ({featureUsage} /{" "}
{featureAllocation})
</div>
);
}
return isFeatureEnabled ? <Feature /> : <NoAccess />;
};
Note: useSchematicIsPending is checking if entitlement data has been loaded, typically via identify. It should, therefore, be used to wrap flag and entitlement checks, but never the initial call to identify.
For features metered by credit burndown, the same entitlement object carries the company's credit position:
creditId | string | undefined | The ID of the credit funding this feature |
creditSettled | number | undefined | The spendable balance, including any amount held by an open lease. This is the number to show end users |
creditRemaining | number | undefined | The balance available to fund new consumption, excluding any open lease hold |
creditReserved | number | undefined | The unspent amount held by an open credit lease, 0 when none is open |
All four are undefined when the feature is not credit-based.
import { useSchematicEntitlement } from "@schematichq/schematic-react";
import { Feature, OutOfCredits } from "./components";
const MyComponent = () => {
const { creditSettled, value: isFeatureEnabled } =
useSchematicEntitlement("my-flag-key");
if (!isFeatureEnabled) {
return <OutOfCredits />;
}
return <Feature creditsRemaining={creditSettled} />;
};
These values refresh with each flag check. For a balance that also updates on the credit partials arriving between checks, pass creditId to useSchematicCreditBalance instead.
Usage warnings
If a usage warning is configured on the entitlement, the hook returns it as warningTiers, so you can warn a customer before they hit the limit rather than after:
warningTiers | WarningTier[] | undefined | The usage warning thresholds configured on the entitlement, each a { key, value } pair in the entitlement's usage units. undefined when none are configured |
softLimit | number | undefined | For usage-based pricing, the soft limit for overage charges or the next tier boundary |
The dashboard writes a single tier under the key default.
import { useSchematicEntitlement } from "@schematichq/schematic-react";
import { Feature, ApproachingLimit } from "./components";
const MyComponent = () => {
const { featureUsage, warningTiers } =
useSchematicEntitlement("my-flag-key");
const warning = warningTiers?.find((tier) => tier.key === "default");
const approachingLimit =
typeof featureUsage === "number" &&
typeof warning?.value === "number" &&
featureUsage >= warning.value;
return (
<>
{approachingLimit && <ApproachingLimit limit={warning.value} />}
<Feature />
</>
);
};
Company plan information
To access the current company's plan and trial status, you can use the useSchematicPlan hook:
import { useSchematicPlan } from "@schematichq/schematic-react";
const MyComponent = () => {
const plan = useSchematicPlan();
if (!plan) {
return <div>No plan assigned</div>;
}
return (
<div>
<p>Current plan: {plan.name}</p>
{plan.trialStatus === "active" && (
<p>Trial ends: {plan.trialEndDate?.toLocaleDateString()}</p>
)}
{plan.trialStatus === "expired" && (
<p>Your trial has ended. <a href="/upgrade">Upgrade now</a></p>
)}
</div>
);
};
The hook returns an object with the following properties:
id | string | The plan ID |
name | string | The plan name |
trialEndDate | Date | undefined | The trial end date, if the company has or had a trial |
trialStatus | "active" | "expired" | "converted" | undefined | The company's trial status: active if the trial is ongoing, expired if the trial ended without conversion, converted if the company converted to a paid plan, or undefined if the company has never trialed |
Credit balances
To display a company's credit balance, use the useSchematicCreditBalance hook. It is keyed by credit ID and updates reactively as the balance changes over the DataStream:
import { useSchematicCreditBalance } from "@schematichq/schematic-react";
const CreditMeter = () => {
const { balance, isLoading } = useSchematicCreditBalance("credit-id");
if (isLoading) {
return <div>Loading…</div>;
}
return <div>{balance} credits remaining</div>;
};
The hook returns an object with the following properties:
balance | number | The spendable balance, or 0 while loading or when the company holds no balance in this credit |
isLoading | boolean | true while the balance is still loading and no value has arrived yet |
The credit ID is available on a feature's entitlement, and the hook accepts string | undefined, so you can feed it straight through without waiting for the check to arrive:
const CreditMeter = () => {
const { creditId } = useSchematicEntitlement("my-flag-key");
const { balance, isLoading } = useSchematicCreditBalance(creditId);
if (isLoading) {
return <div>Loading…</div>;
}
return <div>{balance} credits remaining</div>;
};
While creditId is undefined, the hook reports the client's loading state and a balance of 0.
Credit spend policies
To show the spend limits that bind the current company and user, use the useSchematicCreditSpendPolicies hook. It updates over the DataStream, so a policy edited or deleted in the dashboard reaches the component without a refetch:
import { useSchematicCreditSpendPolicies } from "@schematichq/schematic-react";
const SpendLimits = () => {
const { policies, isLoading } = useSchematicCreditSpendPolicies();
if (isLoading) {
return <div>Loading…</div>;
}
return (
<ul>
{policies.map((policy) => (
<li key={policy.id}>
{policy.kind === "window" && policy.window
? `${policy.scope} limit: ${policy.consumed} of ${policy.limit} credits used this ${policy.window.unit}`
: `${policy.scope} limit: ${policy.limit} credits per request`}
</li>
))}
</ul>
);
};
policies | CreditSpendPolicies | Company-scope policies first, then the user's own; empty when none bind |
isLoading | boolean | true while the policies are still loading and nothing has arrived yet |
A per_draw policy caps a single draw. A window policy caps what can be spent in one period: consumed is what the current period has spent, resetsAt is when the period ends, and window names the period. Each new spend sends an updated consumed. Once resetsAt has passed, read consumed as 0 until the next update arrives.
The policies are advisory for display: the server and the flag check enforce them.
Fallback Behavior
The SDK includes built-in fallback behavior you can use to ensure your application continues to function even when unable to reach Schematic (e.g., during service disruptions or network issues).
Flag Check Fallbacks
When flag checks cannot reach Schematic, they use fallback values in the following priority order:
- Callsite fallback - fallback values can be provided directly in the hook options
- Initialization defaults - fallback values configured via
flagCheckDefaults or flagValueDefaults options when initializing the provider
- Default value - Returns
false if no fallback is configured
import { useSchematicFlag } from "@schematichq/schematic-react";
const MyComponent = () => {
const isFeatureEnabled = useSchematicFlag("feature-flag", {
fallback: true,
});
return isFeatureEnabled ? <Feature /> : <Fallback />;
};
import { SchematicProvider } from "@schematichq/schematic-react";
ReactDOM.render(
<SchematicProvider
publishableKey="your-publishable-key"
flagValueDefaults={{
"feature-flag": true, // Used if API request fails and no callsite fallback
}}
flagCheckDefaults={{
"another-flag": {
flag: "another-flag",
value: true,
reason: "Default value",
},
}}
>
<App />
</SchematicProvider>,
document.getElementById("root"),
);
Event Queueing and Retry
When events (track, identify) cannot be sent due to network issues, they are automatically queued and retried:
- Events are queued in memory (up to 100 events by default, configurable via
maxEventQueueSize)
- Failed events are retried with exponential backoff (up to 5 attempts by default, configurable via
maxEventRetries)
- Events are automatically flushed when the network connection is restored
- Events queued when the page is hidden are sent when the page becomes visible
WebSocket Fallback
In WebSocket mode, if the WebSocket connection fails, the SDK will provide the last known value or the configured fallback values as outlined above. The WebSocket will also automatically attempt to re-establish its connection with Schematic using an exponential backoff.
React Native
Handling app background/foreground
When a React Native app is backgrounded for an extended period, the WebSocket connection may be closed by the OS. When the app returns to the foreground, the connection will automatically reconnect, but this happens on an exponential backoff timer which may cause a delay before fresh flag values are available.
For cases where you need immediate flag updates when returning to the foreground (e.g., after an in-app purchase), you can use one of these methods to re-establish the connection:
forceReconnect(): Always closes and re-establishes the WebSocket connection, guaranteeing fresh values
reconnectIfNeeded(): Only reconnects if the current connection is unhealthy (more efficient for frequent foreground events)
import { useSchematic } from "@schematichq/schematic-react";
import { useEffect } from "react";
import { AppState } from "react-native";
const SchematicAppStateHandler = () => {
const { client } = useSchematic();
useEffect(() => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") {
client.forceReconnect();
}
});
return () => subscription.remove();
}, [client]);
return null;
};
Render this inside your SchematicProvider.
Troubleshooting
For debugging and development, Schematic supports two special modes:
Debug Mode
Enables console logging of all Schematic operations:
import { SchematicProvider } from "@schematichq/schematic-react";
ReactDOM.render(
<SchematicProvider publishableKey="your-publishable-key" debug={true}>
<App />
</SchematicProvider>,
document.getElementById("root"),
);
Offline Mode
Prevents network requests and returns fallback values for all flag checks:
import { SchematicProvider } from "@schematichq/schematic-react";
ReactDOM.render(
<SchematicProvider publishableKey="your-publishable-key" offline={true}>
<App />
</SchematicProvider>,
document.getElementById("root"),
);
Offline mode automatically enables debug mode to help with troubleshooting.
License
MIT
Support
Need help? Please open a GitHub issue or reach out to support@schematichq.com and we'll be happy to assist.