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
$# or
$yarn add @schematichq/schematic-react
$# or
$pnpm add @schematichq/schematic-react

Usage

SchematicProvider

You can use the SchematicProvider to wrap your application and provide the Schematic instance to all components:

1import { SchematicProvider } from "@schematichq/schematic-react";
2
3ReactDOM.render(
4 <SchematicProvider publishableKey="your-publishable-key">
5 <App />
6 </SchematicProvider>,
7 document.getElementById("root"),
8);

Setting context

To set the user context for events and flag checks, you can use the identify function provided by the useSchematicEvents hook:

1import { useSchematicEvents } from "@schematichq/schematic-react";
2
3const MyComponent = () => {
4 const { identify } = useSchematicEvents();
5
6 useEffect(() => {
7 identify({
8 keys: { id: "my-user-id" },
9 company: {
10 keys: { id: "my-company-id" },
11 traits: { location: "Atlanta, GA" },
12 },
13 });
14 }, []);
15
16 return <div>My Component</div>;
17};

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:

1import { useSchematicEvents } from "@schematichq/schematic-react";
2
3const MyComponent = () => {
4 const { track } = useSchematicEvents();
5
6 useEffect(() => {
7 track({ event: "query" });
8 }, []);
9
10 return <div>My Component</div>;
11};

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:

1track({ event: "query", quantity: 10 });

Checking flags

To check a flag, you can use the useSchematicFlag hook:

1import { useSchematicFlag } from "@schematichq/schematic-react";
2import { Feature, Fallback } from "./components";
3
4const MyComponent = () => {
5 const isFeatureEnabled = useSchematicFlag("my-flag-key");
6
7 return isFeatureEnabled ? <Feature /> : <Fallback />;
8};

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:

1import {
2 useSchematicEntitlement,
3 useSchematicIsPending,
4} from "@schematichq/schematic-react";
5import { Feature, Loader, NoAccess } from "./components";
6
7const MyComponent = () => {
8 const schematicIsPending = useSchematicIsPending();
9 const {
10 featureAllocation,
11 featureUsage,
12 featureUsageExceeded,
13 value: isFeatureEnabled,
14 } = useSchematicEntitlement("my-flag-key");
15
16 // loading state
17 if (schematicIsPending) {
18 return <Loader />;
19 }
20
21 // usage exceeded state
22 if (featureUsageExceeded) {
23 return (
24 <div>
25 You have used all of your usage ({featureUsage} /{" "}
26 {featureAllocation})
27 </div>
28 );
29 }
30
31 // either feature state or "no access" state
32 return isFeatureEnabled ? <Feature /> : <NoAccess />;
33};

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.

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:

  1. Callsite fallback - fallback values can be provided directly in the hook options
  2. Initialization defaults - fallback values configured via flagCheckDefaults or flagValueDefaults options when initializing the provider
  3. Default value - Returns false if no fallback is configured
1// Provide a fallback value at the callsite
2import { useSchematicFlag } from "@schematichq/schematic-react";
3
4const MyComponent = () => {
5 const isFeatureEnabled = useSchematicFlag("feature-flag", {
6 fallback: true, // Used if API request fails
7 });
8
9 return isFeatureEnabled ? <Feature /> : <Fallback />;
10};
11
12// Or configure defaults at initialization
13import { SchematicProvider } from "@schematichq/schematic-react";
14
15ReactDOM.render(
16 <SchematicProvider
17 publishableKey="your-publishable-key"
18 flagValueDefaults={{
19 "feature-flag": true, // Used if API request fails and no callsite fallback
20 }}
21 flagCheckDefaults={{
22 "another-flag": {
23 flag: "another-flag",
24 value: true,
25 reason: "Default value",
26 },
27 }}
28 >
29 <App />
30 </SchematicProvider>,
31 document.getElementById("root"),
32);

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 it’s 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)
1import { useSchematic } from "@schematichq/schematic-react";
2import { useEffect } from "react";
3import { AppState } from "react-native";
4
5const SchematicAppStateHandler = () => {
6 const { client } = useSchematic();
7
8 useEffect(() => {
9 const subscription = AppState.addEventListener("change", (state) => {
10 if (state === "active") {
11 // Use forceReconnect() for guaranteed fresh values
12 client.forceReconnect();
13 // Or use reconnectIfNeeded() to skip if connection is healthy
14 // client.reconnectIfNeeded();
15 }
16 });
17 return () => subscription.remove();
18 }, [client]);
19
20 return null;
21};

Render this inside your SchematicProvider.

Troubleshooting

For debugging and development, Schematic supports two special modes:

Debug Mode

Enables console logging of all Schematic operations:

1// Enable at initialization
2import { SchematicProvider } from "@schematichq/schematic-react";
3
4ReactDOM.render(
5 <SchematicProvider publishableKey="your-publishable-key" debug={true}>
6 <App />
7 </SchematicProvider>,
8 document.getElementById("root"),
9);
10
11// Or via URL parameter
12// https://yoursite.com/?schematic_debug=true

Offline Mode

Prevents network requests and returns fallback values for all flag checks:

1// Enable at initialization
2import { SchematicProvider } from "@schematichq/schematic-react";
3
4ReactDOM.render(
5 <SchematicProvider publishableKey="your-publishable-key" offline={true}>
6 <App />
7 </SchematicProvider>,
8 document.getElementById("root"),
9);
10
11// Or via URL parameter
12// https://yoursite.com/?schematic_offline=true

Offline mode automatically enables debug mode to help with troubleshooting.

License

MIT

Support

Need help? Please open a GitHub issue or reach out to [email protected] and we’ll be happy to assist.

Next.js

If you’re building with Next.js, we recommend reading our Next.js SDK guide for more detailed recommendations on how implement Schematic in your Next.js application.