ML — Model Deployment

Model Deployment for React Native Apps

Direct answer

Run a model on the device when you need offline use, privacy, zero per-request cost or instant small tasks — classification, OCR, transcription, short summaries and rewrites. Call a cloud API for frontier-level reasoning, long documents and anything you must change without shipping an app update. In React Native you have three practical routes: react-native-executorch for on-device LLMs and vision models (New Architecture, React Native 0.83+ or Expo SDK 55+ development builds), the platform's own models — Apple's Foundation Models framework and Google's Gemini Nano via ML Kit GenAI — through a native module, and a hybrid router that tries the device first and falls back to the API.

On-device AI stopped being a research demo once Apple and Google started shipping language models inside the operating system and React Native libraries made it possible to run open models from JavaScript. That doesn't mean everything should run on the phone. This guide is the decision framework and the implementation patterns for putting models into a React Native app without breaking app size, battery or the user's patience.

React Native appAI request AI routertask · privacy · networkdevice ready? On-device modeloffline · private · no per-call cost Cloud LLM APIfrontier quality · long context fallback

Key facts, with sources

  • Apple's on-device foundation model is about 3 billion parameters, compressed to 2 bits per weight, and developers get direct access to it through the Foundation Models framework, including guided generation and tool calling. (Apple Machine Learning Research)
  • Google's ML Kit GenAI APIs run Gemini Nano on-device through Android's AICore system service, offering summarization, proofreading, rewriting and image description without sending data to a server. (Android Developers)
  • react-native-executorch, Software Mansion's on-device inference library built on PyTorch's ExecuTorch runtime, requires the New Architecture, React Native 0.83+ or Expo SDK 55+ with development builds (not Expo Go), iOS 17+ and Android 13+. (react-native-executorch README)

On-device vs cloud: the decision table

The choice is per feature, not per app. A notes app might summarize locally, transcribe locally and still send “rewrite this as a proposal” to a cloud model. Decide each feature against the same handful of questions.

QuestionFavours on-deviceFavours cloud API
Must it work offline?Yes — field work, travel, poor networksNo
Is the data sensitive?Health, finance, private messagesData already lives on your server
How hard is the task?Classify, extract, OCR, transcribe, short summariesMulti-step reasoning, long documents, code
Cost per request?Zero marginal cost after downloadPay per token; scales with usage
How often will it change?Stable behaviour, versioned with the appPrompt and model swaps without an app release
Device coverage?Recent phones only (RAM, OS version)Every device with a network
Most production apps end up hybrid: on-device for small, private, frequent tasks; cloud for the hard ones.

Three ways to run models in a React Native app

Route one is react-native-executorch. It runs exported open models — language models, vision, speech-to-text, text-to-speech — from JavaScript hooks, with model files downloaded at runtime. It needs the New Architecture and a development build; it will not run in Expo Go.

Route two is the operating system's own model. On iOS, Apple's Foundation Models framework exposes the on-device model behind Apple Intelligence; on Android, ML Kit GenAI exposes Gemini Nano through AICore. There's no model to download or ship, but availability depends on the device and OS version, and you reach both through a small native module (an Expo module works well).

Route three is classic, small ML models — image classification, object detection, custom tabular models — through runtimes like Core ML on iOS and LiteRT (formerly TensorFlow Lite) on Android, typically a few megabytes and the right tool when you don't need a language model at all.

On-device chat with react-native-executorch (from the library quickstart)
import { Button, View } from 'react-native';
import { models, useLLMChatSession } from 'react-native-executorch';

export function App() {
  const session = useLLMChatSession(models.llm.LFM2_5_1_2B.DEFAULT);

  const handleGenerate = async () => {
    if (!session.isReady || !session.sendMessage) return;
    const turn = await session.sendMessage(
      'Explain on-device AI in one sentence.',
      (token) => console.log(token) // stream tokens into your UI
    );
    console.log('Result messages:', turn.messages);
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button
        title={session.isReady ? 'Generate' : 'Loading model ' + session.downloadProgress.toFixed(0) + '%'}
        onPress={handleGenerate}
        disabled={!session.isReady}
      />
    </View>
  );
}

Using the platform model through an Expo native module

Platform models are attractive because the model is already on the device and maintained by the OS vendor. The integration is a thin native module: check availability, run the prompt, return text. On iOS the Foundation Models framework requires a recent OS and an Apple Intelligence-capable device, so the module must report unavailability cleanly and let JavaScript fall back to another route.

Keep the JavaScript interface identical across platforms — one isAvailable() and one respond() — and implement it with Foundation Models on iOS and ML Kit GenAI on Android. The rest of the app never needs to know which model answered.

ios/OnDeviceLLMModule.swift — Expo module wrapping Apple Foundation Models
import ExpoModulesCore
#if canImport(FoundationModels)
import FoundationModels
#endif

public class OnDeviceLLMModule: Module {
  public func definition() -> ModuleDefinition {
    Name("OnDeviceLLM")

    Function("isAvailable") { () -> Bool in
      #if canImport(FoundationModels)
      if #available(iOS 26.0, *) {
        return SystemLanguageModel.default.availability == .available
      }
      #endif
      return false
    }

    AsyncFunction("respond") { (prompt: String) async throws -> String in
      #if canImport(FoundationModels)
      if #available(iOS 26.0, *) {
        let session = LanguageModelSession()
        let response = try await session.respond(to: prompt)
        return response.content
      }
      #endif
      throw Exception(name: "Unavailable", description: "On-device model not available")
    }
  }
}

The hybrid router: device first, cloud fallback

eligible task? model ready? run on device on failure: cloudunless device-only Log the route per request to see who actually benefits from on-device

A router keeps the policy in one place. It decides per request whether the task is eligible for on-device processing, checks that the local model is actually ready (downloaded, supported on this device, not low on battery if you care), and falls back to the cloud API if anything fails. Sensitive tasks can be marked device-only so they never leave the phone, even on failure — in that case the right fallback is a clear message, not a silent upload.

Log which route served each request. Those numbers tell you how many users actually benefit from the on-device path and whether its quality holds up compared with the cloud answers.

ai/router.ts — one entry point for every AI feature
type Task = 'summarize' | 'classify' | 'rewrite' | 'reason';
type Policy = { deviceEligible: boolean; deviceOnly?: boolean };

const POLICY: Record<Task, Policy> = {
  summarize: { deviceEligible: true },
  classify: { deviceEligible: true },
  rewrite: { deviceEligible: true },
  reason: { deviceEligible: false }, // hard tasks go to the cloud
};

export async function runAI(task: Task, input: string, opts: { sensitive?: boolean } = {}) {
  const policy = POLICY[task];
  const deviceOnly = policy.deviceOnly || opts.sensitive;

  if (policy.deviceEligible && (await onDevice.isReady())) {
    try {
      const text = await onDevice.run(task, input);
      track('ai_route', { task, route: 'device' });
      return text;
    } catch (e) {
      track('ai_route_error', { task, route: 'device' });
      if (deviceOnly) throw e; // never upload sensitive input as a fallback
    }
  } else if (deviceOnly) {
    throw new Error('This feature needs an on-device model that is not available here.');
  }

  const text = await cloud.run(task, input); // your backend proxies the LLM API
  track('ai_route', { task, route: 'cloud' });
  return text;
}

Shipping concerns: size, memory, battery and updates

Model size is the first constraint users feel. A useful rule of thumb for language models is parameters × bits per weight ÷ 8: a 1-billion-parameter model is roughly 0.5 GB at 4-bit and roughly 1 GB at 8-bit, before runtime overhead. Don't bundle that in the app binary. Download it after install, preferably on Wi-Fi, show progress, store it where the OS won't purge it unexpectedly, and version the file so you can ship an improved model without an app update.

Memory is the second. Loading a language model needs free RAM well beyond the file size on some devices, so gate the feature on device capability and handle out-of-memory failures by falling back rather than crashing. Battery and heat are the third: on-device generation is fine for short outputs, but long generations on older phones drain battery noticeably, which is another reason to keep long tasks in the cloud.

Finally, plan for quality checks the same way you would for a cloud model: a small set of real inputs, run on the actual low-end devices you support, compared against the cloud answer before you route traffic on-device.

ConcernWhat goes wrongMitigation
App sizeStore size limits, install drop-offDownload model after install; Wi-Fi + progress UI
RAMCrash or OS kill on loadGate on device class; fall back to cloud
Battery / heatLong generations drain older phonesShort outputs on device; long ones in cloud
OS availabilityPlatform model missing on older devicesisAvailable() check + fallback route
Model updatesStuck with the version you shippedVersioned remote model files
Size estimate rule of thumb: parameters × bits per weight ÷ 8. Real files vary by format and runtime overhead.

When to hire senior help

The pilot-to-production gap is where nearly half of AI projects die, so senior help is most leveraged at the point where a validated prototype needs a serving architecture, rollout plan, and monitoring. An experienced engineer can usually take a working model to a canaried production deployment far faster than a team learning serving infrastructure for the first time, avoiding the 8-month average lag. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.

Bottom line

Dhairya Senjaliya ships ML — Model Deployment projects worldwide — book a scoping call to discuss your specific situation.

Common pitfalls to avoid

  • ✕Treating deployment as a final step instead of designing the serving path early, which is how prototypes stall for the 8-month average Gartner measures
  • ✕Wrapping a notebook in a Flask endpoint with no load testing, then discovering latency and memory limits under real traffic
  • ✕Deploying a new model with no shadow mode or canary phase, so the first regression is discovered by customers
  • ✕Rebuilding features at serving time with different code than training used, producing predictions that never match offline evaluation

Frequently asked questions

Can I run an LLM inside a React Native app?

Yes. react-native-executorch runs exported open language models on-device from JavaScript, and the OS models — Apple Foundation Models on iOS and Gemini Nano via ML Kit GenAI on Android — are reachable through a native module. Expect small models suited to short tasks, not frontier-level reasoning.

Does on-device AI work in Expo?

Yes, with development builds. Libraries like react-native-executorch need native code and the New Architecture, so they don't run in Expo Go; per the library's README it supports Expo SDK 55+ development builds.

Is on-device AI cheaper than an API?

Per request, yes — there's no token bill once the model is on the phone. The costs move elsewhere: engineering time, download bandwidth, device coverage limits and quality testing on low-end phones. For high-volume small tasks it usually wins; for occasional hard tasks the API is simpler.

How do I keep sensitive data off the server?

Mark those features device-only in your router so they never fall back to the cloud, and show a clear message when the device can't run them. Don't silently upload sensitive input when the local model fails.

Should I bundle the model in the app binary?

Usually not. Language models are hundreds of megabytes or more; download them after install, on Wi-Fi where possible, and version them so you can update the model without a store release.

How long does it take to get a model into production?

Gartner's 2024 survey puts the average at 8 months from prototype to production, and only about half of projects complete the journey. Teams that decide the serving architecture, latency budget, and rollback plan during model development, not after, consistently beat that average.

Do we need Kubernetes to serve models?

No; a single containerized service or a managed endpoint from a cloud ML platform serves most early workloads fine. Kubernetes becomes the common choice at scale, with CNCF reporting 66% of organizations hosting generative AI models use it for inference, but adopting it prematurely adds operational burden without benefit.

Batch predictions or a real-time API?

If decisions are consumed on a schedule, such as daily churn scores or weekly forecasts, batch scoring into a database is dramatically cheaper and simpler to operate. Real-time serving is only necessary when the prediction depends on information available seconds before the decision, like fraud checks at checkout.

Bottom line: Dhairya Senjaliya ships ML — Model Deployment projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.

Sources

Related guides

Keep up with new guides

New deep-dive guides on React Native, Python, and AI ship regularly. Subscribe via RSS or follow on LinkedIn.

Want help implementing this?

30-minute scoping call · Clear milestones · Senior engineer ownership