Runtime SDKsReact

React Examples & Patterns

Real-world integration recipes and patterns using the RuntimeHQ React SDK.

React Examples & Patterns

This page contains canonical real-world examples demonstrating how to use @theruntimehq/react to build resilient, operationally-aware applications.

All examples below are automatically synchronized directly from sdks/react/examples.

Zero UI Dependencies

The RuntimeHQ React SDK is a pure state management SDK. You can connect runtime state to standard HTML, Tailwind CSS, or design systems like Shopify Polaris and Checkout Extensibility.

Banners & Status Alerts

Communicate service degradation, scheduled maintenance, and incidents clearly to users.

Application Wide Banner

Business Outcome: Inform all users when the application is degraded, under maintenance, or unavailable.

View source on GitHub ↗

01-application-wide-banner.tsx
/**
 * Business Outcome: Inform all users when the application is degraded, under maintenance, or unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function ApplicationWideBanner() {
  const { runtime, loading } = useRuntimeHQ();

  if (loading || !runtime || runtime.state === "OPERATIONAL") {
    return null;
  }

  return (
    <div className={`banner banner-${runtime.state.toLowerCase()}`}>
      <p>⚠️ {runtime.message}</p>
    </div>
  );
}

Capability Outage Tooltip

Business Outcome: Explain why a specific feature is unavailable.

View source on GitHub ↗

02-capability-outage-tooltip.tsx
/**
 * Business Outcome: Explain why a specific feature is unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function CapabilityOutageTooltip({ children, capabilityName }: { children: React.ReactNode, capabilityName: string }) {
  const { isOperational, message } = useCapability(capabilityName);

  if (!isOperational) {
    return (
      <div className="tooltip-wrapper" title={message}>
        <div className="disabled-element">{children}</div>
      </div>
    );
  }

  return <>{children}</>;
}

Degraded Experience Message

Business Outcome: Communicate reduced functionality without blocking users.

View source on GitHub ↗

07-degraded-experience-message.tsx
/**
 * Business Outcome: Communicate reduced functionality without blocking users.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function SearchBar() {
  const { isDegraded, message } = useCapability("search");

  return (
    <div>
      <input type="search" placeholder="Search..." />
      {isDegraded && (
        <small className="warning-text">Search might be slower than usual: {message}</small>
      )}
    </div>
  );
}

Runtime Status Indicator

Business Outcome: Show operational status in the application header, footer, or navigation.

View source on GitHub ↗

08-runtime-status-indicator.tsx
/**
 * Business Outcome: Show operational status in the application header, footer, or navigation.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function StatusIndicator() {
  const { runtime } = useRuntimeHQ();
  if (!runtime) return null;

  const colorMap: Record<string, string> = {
    OPERATIONAL: "green",
    DEGRADED: "yellow",
    MAINTENANCE: "blue",
    OUTAGE: "red",
  };

  return (
    <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
      <div style={{ width: 10, height: 10, borderRadius: "50%", backgroundColor: colorMap[runtime.state] }} />
      <span>System Status</span>
    </div>
  );
}

Outage Toast Notifications

Business Outcome: Notify users immediately when runtime state changes occur.

View source on GitHub ↗

14-outage-toast-notifications.tsx
/**
 * Business Outcome: Notify users immediately when runtime state changes occur.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React, { useEffect, useRef } from "react";
import { useRuntimeHQ } from "@theruntimehq/react";
// import { toast } from "react-hot-toast";

export function RuntimeStateNotifier() {
  const { runtime } = useRuntimeHQ();
  const previousState = useRef<string | null>(null);

  useEffect(() => {
    if (runtime && previousState.current && runtime.state !== previousState.current) {
      if (runtime.state === "OUTAGE") {
        console.log(`Toast Warning: ${runtime.message}`); // toast.error(runtime.message);
      } else if (runtime.state === "OPERATIONAL") {
        console.log("Toast Success: All systems operational!"); // toast.success("All systems operational!");
      }
    }
    if (runtime) {
      previousState.current = runtime.state;
    }
  }, [runtime]);

  return null;
}

Feature Gating & Workflow Protection

Protect write operations and mission-critical transactions when backend capabilities fail.

Feature Gating

Business Outcome: Hide unavailable functionality from users.

View source on GitHub ↗

03-feature-gating.tsx
/**
 * Business Outcome: Hide unavailable functionality from users.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function FeatureGate({ capabilityName, children }: { capabilityName: string, children: React.ReactNode }) {
  const { isOperational } = useCapability(capabilityName);

  if (!isOperational) {
    return null; // Hide the feature completely
  }

  return <>{children}</>;
}

Disable Checkout When Payments Down

Business Outcome: Prevent purchases when the payments capability is unavailable.

View source on GitHub ↗

04-disable-checkout-when-payments-down.tsx
/**
 * Business Outcome: Prevent purchases when the payments capability is unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function CheckoutButton() {
  const { isOperational, message } = useCapability("payments");

  return (
    <button disabled={!isOperational}>
      {!isOperational ? `Checkout Disabled: ${message}` : "Complete Checkout"}
    </button>
  );
}

Disable Document Upload During Maintenance

Business Outcome: Prevent uploads while the upload capability is under maintenance.

View source on GitHub ↗

05-disable-document-upload-during-maintenance.tsx
/**
 * Business Outcome: Prevent uploads while the upload capability is under maintenance.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function DocumentUploader() {
  const { isMaintenance, message } = useCapability("uploads");

  if (isMaintenance) {
    return <div className="maintenance-notice">Uploads are currently under maintenance: {message}</div>;
  }

  return <input type="file" />;
}

Read Only Mode During Outage

Business Outcome: Keep the application usable while blocking write operations.

View source on GitHub ↗

06-read-only-mode-during-outage.tsx
/**
 * Business Outcome: Keep the application usable while blocking write operations.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function SettingsForm() {
  const { runtime } = useRuntimeHQ();
  const isReadOnly = runtime && (runtime.state === "OUTAGE" || runtime.state === "MAINTENANCE");

  return (
    <form>
      {isReadOnly && <p>System is in read-only mode. Changes cannot be saved at this time.</p>}
      <input type="text" defaultValue="User Name" disabled={isReadOnly} />
      <button type="submit" disabled={isReadOnly}>Save Changes</button>
    </form>
  );
}

Maintenance Lock Screen

Business Outcome: Restrict access to workflows during active maintenance windows.

View source on GitHub ↗

19-maintenance-lock-screen.tsx
/**
 * Business Outcome: Restrict access to workflows during active maintenance windows.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function MaintenanceLockScreen({ children }: { children: React.ReactNode }) {
  const { runtime } = useRuntimeHQ();

  if (runtime?.state === "MAINTENANCE") {
    return (
      <div className="lock-screen">
        <h2>Scheduled Maintenance</h2>
        <p>{runtime.message}</p>
        <p>Please check back later.</p>
      </div>
    );
  }

  return <>{children}</>;
}

Routing & Navigation Guards

Prevent navigation to broken views and route users to graceful operational fallbacks.

Runtime Aware Navigation

Business Outcome: Hide or disable navigation items for unavailable capabilities.

View source on GitHub ↗

10-runtime-aware-navigation.tsx
/**
 * Business Outcome: Hide or disable navigation items for unavailable capabilities.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function NavigationBar() {
  const { hasCapability, getCapabilityState } = useRuntimeHQ();

  const navItems = [
    { label: "Dashboard", href: "/dashboard" },
    { label: "Reports", href: "/reports", capability: "reporting" },
  ];

  return (
    <nav>
      {navItems.map((item) => {
        if (item.capability && hasCapability(item.capability)) {
          const cap = getCapabilityState(item.capability);
          if (cap?.state === "OUTAGE") return null; // Hide reports tab during outage
        }
        return <a key={item.label} href={item.href}>{item.label}</a>;
      })}
    </nav>
  );
}

Runtime Aware Routing

Business Outcome: Prevent access to routes backed by unavailable capabilities.

View source on GitHub ↗

11-runtime-aware-routing.tsx
/**
 * Business Outcome: Prevent access to routes backed by unavailable capabilities.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React, { useEffect } from "react";
import { useCapability } from "@theruntimehq/react";
// Assuming react-router-dom or similar
// import { useNavigate } from "react-router-dom";

export function ProtectedRoute({ capability, children }: { capability: string, children: React.ReactNode }) {
  const { isOutage, loading } = useCapability(capability);
  // const navigate = useNavigate();

  useEffect(() => {
    if (!loading && isOutage) {
      // navigate("/unavailable");
      console.log("Redirect to unavailable page");
    }
  }, [loading, isOutage]);

  if (loading) return <div>Loading...</div>;
  return <>{children}</>;
}

Runtime Aware Redirection

Business Outcome: Automatically redirect users when a capability becomes unavailable.

View source on GitHub ↗

12-runtime-aware-redirection.tsx
/**
 * Business Outcome: Automatically redirect users when a capability becomes unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React, { useEffect } from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function AutomaticRedirector() {
  const { runtime } = useRuntimeHQ();

  useEffect(() => {
    if (runtime?.state === "OUTAGE") {
      window.location.href = "/system-down";
    }
  }, [runtime?.state]);

  return null; // Invisible observer component
}

Runtime Aware Fallback Route

Business Outcome: Redirect users to an alternative workflow when the primary capability is unavailable.

View source on GitHub ↗

13-runtime-aware-fallback-route.tsx
/**
 * Business Outcome: Redirect users to an alternative workflow when the primary capability is unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function VideoPlayerPage() {
  const { isOutage } = useCapability("hd-streaming");

  if (isOutage) {
    return (
      <div>
        <p>HD Streaming is currently unavailable. Falling back to Standard Definition.</p>
        <StandardDefPlayer />
      </div>
    );
  }

  return <HighDefPlayer />;
}

function HighDefPlayer() { return <div>HD Player</div>; }
function StandardDefPlayer() { return <div>SD Player</div>; }

Runtime Aware Error Page

Business Outcome: Replace generic errors with operationally-aware messaging.

View source on GitHub ↗

17-runtime-aware-error-page.tsx
/**
 * Business Outcome: Replace generic errors with operationally-aware messaging.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function GlobalErrorFallback({ error }: { error: Error }) {
  const { runtime } = useRuntimeHQ();

  if (runtime?.state === "OUTAGE") {
    return (
      <div className="known-outage-screen">
        <h1>We're experiencing an outage</h1>
        <p>Our engineers are working on it. {runtime.message}</p>
      </div>
    );
  }

  return (
    <div className="generic-error-screen">
      <h1>Something went wrong</h1>
      <p>{error.message}</p>
    </div>
  );
}

Runtime Aware Empty State

Business Outcome: Show meaningful empty states when functionality is unavailable.

View source on GitHub ↗

18-runtime-aware-empty-state.tsx
/**
 * Business Outcome: Show meaningful empty states when functionality is unavailable.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

export function InvoiceList({ invoices }: { invoices: any[] }) {
  const { isOutage, message } = useCapability("billing");

  if (invoices.length === 0) {
    if (isOutage) {
      return (
        <div className="empty-state warn">
          <p>We cannot fetch your invoices right now due to a system issue: {message}</p>
        </div>
      );
    }
    return <p>You have no invoices.</p>;
  }

  return <ul>{invoices.map(i => <li key={i.id}>{i.id}</li>)}</ul>;
}

Dashboards & Operational Monitoring

Build live health dashboards, embedded widgets, and multi-app operations centers.

Customer Facing Status Page

Business Outcome: Build a public status page powered by RuntimeHQ.

View source on GitHub ↗

09-customer-facing-status-page.tsx
/**
 * Business Outcome: Build a public status page powered by RuntimeHQ.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function StatusPage() {
  const { runtime, loading } = useRuntimeHQ();

  if (loading) return <div>Loading status...</div>;
  if (!runtime) return <div>Unable to load status</div>;

  return (
    <div className="status-container">
      <h1>System Status: {runtime.state}</h1>
      <p>{runtime.message}</p>
      <ul className="capabilities-list">
        {runtime.capabilityStates.map((cap) => (
          <li key={cap.capabilityName}>
            <strong>{cap.capabilityName}:</strong> {cap.state}
          </li>
        ))}
      </ul>
    </div>
  );
}

Runtime Dashboard

Business Outcome: Build an operational dashboard displaying application health and capability health.

View source on GitHub ↗

15-runtime-dashboard.tsx
/**
 * Business Outcome: Build an operational dashboard displaying application health and capability health.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function OperationsDashboard() {
  const { runtime } = useRuntimeHQ();

  if (!runtime) return null;

  return (
    <div className="dashboard">
      <h2>App Health: {runtime.state}</h2>
      <p>Last checked: {runtime.lastSuccessfulFetchAt.toLocaleTimeString()}</p>
      <div className="capabilities-grid">
        {runtime.capabilityStates.map((cap) => (
          <div key={cap.capabilityName} className={`card ${cap.state.toLowerCase()}`}>
            <h3>{cap.capabilityName}</h3>
            <p>{cap.state}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

Multi Application Operations Center

Business Outcome: Monitor multiple applications from a unified screen.

View source on GitHub ↗

16-multi-application-operations-center.tsx
/**
 * Business Outcome: Monitor multiple applications from a unified screen.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQState } from "@theruntimehq/react";

export function MultiAppDashboard() {
  const app1 = useRuntimeHQState({ runtimeKey: "rt_prod_app1" });
  const app2 = useRuntimeHQState({ runtimeKey: "rt_prod_app2" });

  return (
    <div className="multi-app-grid">
      <div className="app-card">
        <h3>Frontend App</h3>
        <p>Status: {app1.loading ? "Loading..." : app1.runtime?.state}</p>
      </div>
      <div className="app-card">
        <h3>Backend API</h3>
        <p>Status: {app2.loading ? "Loading..." : app2.runtime?.state}</p>
      </div>
    </div>
  );
}

Live System Health Widget

Business Outcome: Embed a reusable health widget anywhere in the application.

View source on GitHub ↗

20-live-system-health-widget.tsx
/**
 * Business Outcome: Embed a reusable health widget anywhere in the application.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useRuntimeHQ } from "@theruntimehq/react";

export function HealthWidget() {
  const { runtime, error } = useRuntimeHQ();

  if (error) {
    return <div className="widget error">Unable to check system health</div>;
  }

  if (!runtime) return null;

  return (
    <div className={`health-widget ${runtime.dataStatus === 'STALE' ? 'stale' : 'live'}`}>
      <strong>{runtime.state}</strong>
      <span>Data is {runtime.dataStatus}</span>
    </div>
  );
}

Adaptive Client Performance & Setup

Adapt client request behavior under degraded backend conditions and set up resilient providers.

Production Ready Provider

Business Outcome: Complete production integration including provider setup, refresh handling, and resilience patterns.

View source on GitHub ↗

21-production-ready-provider.tsx
/**
 * Business Outcome: Complete production integration including provider setup, refresh handling, and resilience patterns.
 */
import React from "react";
import { RuntimeHQProvider, useRuntimeHQ } from "@theruntimehq/react";

function AppContent() {
  const { error, runtime } = useRuntimeHQ();

  if (error && !runtime) {
    // Failed to load initial state and no cache available
    return <div>Failed to initialize application safety checks. Please refresh.</div>;
  }

  return (
    <main>
      <h1>My Application</h1>
      <p>App Status: {runtime?.state || "Initializing..."}</p>
    </main>
  );
}

export function App() {
  return (
    <RuntimeHQProvider runtimeKey="rt_prod_your_key" intervalSeconds={60}>
      <AppContent />
    </RuntimeHQProvider>
  );
}

Business Outcome: Adapt client input debounce delay to shed backend load during degraded states.

View source on GitHub ↗

22-adaptive-debounce-search.tsx
/**
 * Business Outcome: Adapt client input debounce delay to shed backend load during degraded states.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";

// Generic debounce utility for demonstration
function debounce<T extends (...args: any[]) => void>(fn: T, delayMs: number) {
  let timer: any;
  return (...args: Parameters<T>) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delayMs);
  };
}

export function AdaptiveSearchInput({ onSearch }: { onSearch: (query: string) => void }) {
  const { isOutage, isDegraded, message } = useCapability("search");

  // Dynamically back off request frequency when search capability is degraded
  const debounceDelayMs = isDegraded ? 1200 : 300;

  return (
    <div className="search-container">
      <input
        type="search"
        placeholder="Search products..."
        disabled={isOutage}
        onChange={debounce((e: React.ChangeEvent<HTMLInputElement>) => onSearch(e.target.value), debounceDelayMs)}
      />
      {(isOutage || isDegraded) && message && (
        <p className={`status-message ${isOutage ? "outage" : "degraded"}`}>
          {message}
        </p>
      )}
    </div>
  );
}

Ecosystem & Platform Integrations

Safeguard high-stakes merchant and checkout workflows across third-party platforms.

Shopify Polaris Capability Guard

Business Outcome: Protect merchant workflows in Shopify Admin apps using Polaris Banners and disabled action states.

View source on GitHub ↗

23-shopify-polaris-capability-guard.tsx
/**
 * Business Outcome: Protect merchant workflows in Shopify Admin apps using Polaris Banners and disabled action states.
 */
// Note: This component must be rendered inside a <RuntimeHQProvider runtimeKey="...">
import React from "react";
import { useCapability } from "@theruntimehq/react";
import { Page, Banner, Layout, Card, BlockStack, Text } from "@shopify/polaris";

export function ShopifySyncPage() {
  const { isOperational, isOutage, message } = useCapability("inventory_sync");

  return (
    <Page
      title="Inventory Synchronization"
      primaryAction={{
        content: "Sync Catalog Now",
        disabled: !isOperational,
        helpText: !isOperational ? message : undefined,
      }}
    >
      <BlockStack gap="400">
        {!isOperational && message && (
          <Banner tone={isOutage ? "critical" : "warning"}>
            <p>{message}</p>
          </Banner>
        )}

        <Layout>
          <Layout.Section>
            <Card>
              <Text as="p" variant="bodyMd">
                Manage your warehouse and Shopify store inventory stock levels.
              </Text>
            </Card>
          </Layout.Section>
        </Layout>
      </BlockStack>
    </Page>
  );
}

Shopify Checkout UI Extension

Business Outcome: Protect Shopify checkout conversion by failing open and hiding unavailable extension widgets.

View source on GitHub ↗

24-shopify-checkout-ui-extension.tsx
/**
 * Business Outcome: Protect Shopify checkout conversion by failing open and hiding unavailable extension widgets.
 */
// Note: This extension runs in Shopify Checkout Extensibility via Web Workers
import React from "react";
import {
  reactExtension,
  Banner,
  BlockStack,
  Button,
  Text,
} from "@shopify/ui-extensions-react/checkout";
import { RuntimeHQProvider, useCapability } from "@theruntimehq/react";

// Target: Render inside checkout before payment / review block
export default reactExtension("purchase.checkout.block.render", () => (
  // Note: runtimeKey is a public, read-only key that is safe for client-side / checkout exposure.
  // Use `rt_test_...` during local dev (`shopify app dev`) and Checkout Editor simulation,
  // and `rt_prod_...` for live checkout. Can also be dynamically retrieved from extension settings.
  <RuntimeHQProvider runtimeKey="rt_prod_shopify_checkout_key">
    <LoyaltyPointsRedemption />
  </RuntimeHQProvider>
));

function LoyaltyPointsRedemption() {
  const { isOperational, isOutage, isDegraded, message } = useCapability("loyalty_engine");

  // Fail-Open Guidance: Gracefully hide non-essential widgets during outages to avoid disrupting the buyer checkout funnel
  if (isOutage) {
    return null;
  }

  return (
    <BlockStack spacing="loose">
      {isDegraded && message && (
        <Banner status="warning">
          <Text>{message}</Text>
        </Banner>
      )}

      <BlockStack spacing="tight">
        <Text size="medium" emphasis="bold">
          Redeem Loyalty Points
        </Text>
        <Text appearance="subdued">
          Apply your store points for an instant discount.
        </Text>
        <Button
          kind="secondary"
          disabled={!isOperational}
          onPress={() => console.log("Applying points discount...")}
        >
          Apply 500 Points ($5.00 Off)
        </Button>
      </BlockStack>
    </BlockStack>
  );
}

On this page