Skip to content
All articles
BLOG

How to Implement Server-Driven Paywalls in React Native Without Bridge Overhead

Implement cached, native-component React Native paywalls with ONLang, stable rendering, TypeScript contracts, purchase callbacks, and offline fallbacks.

Key Takeaways

  • React Native server-driven paywalls can render registered React components from cached contracts without downloading executable code or requiring a custom TurboModule.
  • The New Architecture reduces old bridge constraints but does not prove zero overhead; stable props, memoization, parsed-contract reuse, and profiling still determine paywall performance.
  • ONLang’s @on-lang/react-native package (React Native 0.74+, Expo or bare) is pure JavaScript with no native module of its own; it supports loading and fallback renderers while preserving existing purchase functions and native billing.

“Without bridge overhead” is an attractive promise and a poor benchmark specification. React Native’s New Architecture, default since version 0.76, uses JSI, Fabric, and TurboModules to replace many asynchronous bridge constraints. It does not make serialization, JavaScript rendering, native view creation, image work, or store-product loading free.

A server-driven paywall adds another risk: parsing a remote document and constructing a new component tree on every render. The solution is not a custom native module by default. It is a small typed contract, registered components, stable identities, cached payloads, and careful profiling.

Avoid unbounded dynamic component trees

A common first implementation downloads arbitrary nested nodes and maps every node through a large switch statement. Each refresh creates new objects, callbacks, and style values. The reconciler then traverses a deep tree while product requests and analytics updates trigger additional renders.

Prefer semantic components such as PaywallIntro, PlanToggle, and PurchaseButton over unrestricted layout nodes. This keeps the contract small and allows each component to own accessibility and styling. Memoize the parsed contract and render only when the composition or relevant selection changes.

Do not put the entire application state in the paywall’s parent. Entitlement updates, experimental assignment, product loading, and selected plan have different lifetimes. A pending purchase should not cause a freshly fetched contract to replace the screen underneath the store sheet.

ONLang uses a registry of application-owned React components. Its SDK renders DivKit-based contracts itself, in JavaScript, using those components, with no WebView and no downloaded executable code. The package has no native module of its own, so there is no custom TurboModule to write. New native primitives still ship with the app; the server selects only registered behavior.

Install and register the real packages

Install the ONLang React Native SDK, persistent storage, and the CLI as a development dependency. Use your project’s package manager; the only pods to install are AsyncStorage’s, because the ONLang SDK itself is plain JavaScript.

npm install @on-lang/react-native @react-native-async-storage/async-storage
npm install --save-dev @on-lang/cli
npx pod-install
npx @on-lang/cli init

A registry declares typed props and product identifiers. It can live beside other ONLang configuration and be checked before publication. The important boundary is that remote values are data passed to existing components, not module names evaluated at runtime.

The following TypeScript example demonstrates the rendering discipline around a tiny registered component. It is ordinary React Native code and can compile in an app with the shown imports.

import React, { memo, useCallback } from "react";
import { Pressable, StyleSheet, Text } from "react-native";

export type PurchaseButtonProps = {
  title: string;
  disabled: boolean;
  onPurchase: () => void;
};

export const PurchaseButton = memo(function PurchaseButton({
  title,
  disabled,
  onPurchase,
}: PurchaseButtonProps) {
  return (
    <Pressable
      accessibilityRole="button"
      accessibilityState={{ disabled }}
      disabled={disabled}
      onPress={onPurchase}
      style={({ pressed }) => [styles.button, pressed && styles.pressed]}
    >
      <Text style={styles.title}>{title}</Text>
    </Pressable>
  );
});

const styles = StyleSheet.create({
  button: {
    minHeight: 48,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 12,
    backgroundColor: "#111827",
    paddingHorizontal: 20,
  },
  pressed: { opacity: 0.75 },
  title: { color: "#FFFFFF", fontSize: 17, fontWeight: "600" },
});

export function usePurchaseHandler(purchase: () => Promise<void>) {
  return useCallback(() => {
    void purchase();
  }, [purchase]);
}

In an ONLang registry, a button like this would either be registered with { interactive: true } and report taps through context.fire(...), or drop its own Pressable so ONLang can wrap it and route the tap; the memoization discipline is the same either way.

React.memo helps only when props remain stable. A newly created inline callback on every parent render defeats part of that benefit, so useCallback and stable product records matter. Profiling should confirm actual waste before adding more memoization.

Render ONLang flows with explicit fallback states

OnlangFlow takes a placement, an onFinished callback, and render hooks for loading and failure states; the registered components come from the registry passed to Onlang.configure. Keep the fallback visually complete and actionable. A spinner is not an offline paywall.

import React from "react";
import { ActivityIndicator, Text, View } from "react-native";
import { OnlangFlow } from "@on-lang/react-native";
import { ExistingPaywall } from "./ExistingPaywall";

export function PaywallScreen({ onClose }: { onClose: () => void }) {
  return (
    <OnlangFlow
      placement="paywall"
      onFinished={(result) => {
        if (result.outcome !== "failed" && result.outcome !== "killed") onClose();
      }}
      renderLoading={() => (
        <View accessibilityLabel="Loading subscription options">
          <ActivityIndicator />
          <Text>Loading your options…</Text>
        </View>
      )}
      renderFallback={() => <ExistingPaywall />}
    />
  );
}

Use the package version’s documented registry and context parameters when composing this screen; the React Native guide contains the complete working setup. If your app shares native code or purchase flows, compare the iOS guide and Android guide to keep behavior aligned.

Do not replace the existing paywall until the fallback itself passes sandbox purchase tests. ONLang outcomes include failed and killed delivery, so application code must own the final fallback. StoreKit 2, Play Billing, RevenueCat, or app-provided purchase functions remain unchanged.

Cache contracts and assignments together

An offline-first resolver should have three sources: a network release when available, the last validated cached release, and a bundled composition for first launch or cache failure. Persist the experiment assignment with the contract so a user does not change arms after every refresh. In ONLang, assignment becomes sticky once the user grants consent and the SDK creates its random install id; before that, the variant is drawn per launch and not counted as an exposure.

ONLang can compose a placement locally for bundling:

onlang compose --placement paywall --locale en --out build/onlang/paywall

The command writes composition.json, manifest.json, and one bundle file per screen. Ship those bundles with the app and return them from the fallback option of Onlang.configure for that placement and locale. At runtime, use network → cache → bundled behavior without making initial presentation wait indefinitely for the network. Revalidate in the background and apply a new composition on the next safe impression.

Keep store-product display prices separate from old payload strings. Cached copy may be acceptable while cached prices, promotions, or trial terms may not. A native purchase layer must reconcile the selected product with current store details.

HTTP caching and application caching are related but not identical. Cache-Control: stale-while-revalidate describes HTTP reuse behavior; it does not automatically implement ONLang’s bundled fallback or experiment persistence. Offline-first dynamic paywalls develops that distinction.

Profile the New Architecture, do not assume it

TurboModules improve native-module integration, and Fabric improves rendering interoperability, but ONLang’s React Native package does not ask you to create a custom TurboModule. The important performance work often lives in JavaScript object creation, JSON parsing, component complexity, and asset decoding.

Use React DevTools and platform profilers on a release build. Measure the interval from placement trigger to an actionable paywall, including product readiness. Compare empty cache, warm cache, bundled fallback, and offline presentation. Include an Android device near the lower end of your supported matrix.

Look for repeated parsing of the same payload, unstable component keys, inline style creation in deep loops, and analytics state that rerenders the entire screen. Do not add native code merely because the word “bridge” appears in an old blog post. First identify whether a measured hotspot crosses a native boundary at all.

Report distributions rather than a universal FPS number. A static paywall may not produce meaningful continuous frame metrics; scroll and selection responsiveness can matter more. Time-to-interactive and dropped work during presentation are more useful than claiming an architecture always renders at 60 fps.

Keep purchase and entitlement state outside remote UI

The selected plan is UI state. A completed transaction and active entitlement are store or backend state. Never serialize an “owned” flag into the paywall contract and trust it after restart. Observe StoreKit, Play Billing, or your subscription provider as the source of truth.

A purchase callback should receive a validated product identifier, not an arbitrary payload. Disable duplicate taps, handle pending transactions, and restore entitlement after process death. Remote copy cannot be allowed to transform a monthly identifier into an annual purchase without registry validation.

Attribution and personalization context should also be allowlisted. Campaign names may arrive asynchronously or not at all; the paywall needs a generic fallback. Acquisition-channel personalization explains how to map attribution into a small safe context.

For AI-generated variants, TypeScript catches shape errors at build time but cannot prove truthful copy or valid offer combinations. Runtime schema and semantic validation remain necessary. Finite hypothesis spaces covers that gate.

Test rendering and operational failure

Create fixtures for every registered component and all supported contract versions. Test long translations, large accessibility fonts, missing images, unavailable products, unknown fields, and invalid actions. Verify screen-reader labels and focus order in both light and dark modes.

Exercise a killed placement and a network failure. ONLang’s CLI provides onlang kill paywall --reason "INC-12" and onlang kill paywall --lift; the application’s renderFallback must remain purchasable. Test that fallback with the same store sandbox accounts as the remote composition.

For experiments, log one exposure per actual impression and preserve assignment across app restarts. Do not count loading placeholders as exposures. Delayed purchase, trial, and refund outcomes need a consistent identity and analysis window. Bandit optimization and holdout incrementality explain the measurement trade-offs.

Ship one controlled variation

Start by reproducing the current paywall with registered React components and a bundled contract. Compare analytics parity and purchase behavior before enabling optimization. Then create one finite copy hypothesis, lint it, publish it, and start an experiment with a deliberate holdout.

onlang hypothesis create --id paywall.cta.copy --kind tokens --screen paywall \
  --key cta.title --rationale "Name the outcome, not the step" \
  --variant "outcome=Get my plan" --variant "trial=Try Pro free for {{trial.annual}}"
onlang lint
ONLANG_TOKEN=onl_sk_… onlang publish
ONLANG_TOKEN=onl_sk_… onlang experiment create --placement paywall --holdout 0.1 --start
ONLANG_TOKEN=onl_sk_… onlang experiment status <id>

The one-hour setup target in the ONLang quickstart is a guided goal, not a measured guarantee. Native project setup, purchase integration, and app-specific testing determine the real time.

ONLang offers full functionality for 14 days per new app, with no card required at signup. Start the trial and profile a real registered component tree on your own devices before committing to a rollout.

Sources