<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap" rel="stylesheet"/>

React Native On-Device LLM: Run Gemma & Llama Locally

By Mihir Pipermitwala · · 9 min read

⚡ TL;DR

Run on-device LLMs in React Native using llama.rn and MediaPipe. Zero API costs, offline AI, private by design — for iOS and Android apps.

On-device LLMs have arrived for React Native. Using optimized quantization and native modules, you can run Gemma 2B or Llama 3.2 1B directly on user devices — no API keys, no cloud costs, complete privacy. I integrated this into a health app; here’s everything I learned.

A note on libraries: this space moves fast and the code below is illustrative rather than a drop-in snippet. llama.rn is real and actively maintained; MediaPipe’s LLM Inference API is real too, but there is no official @react-native-community wrapper — you’ll use a community bridge (e.g. react-native-llm-mediapipe) or write a small native module. Always check the linked repos for the current API before committing to one.

Why On-Device for React Native?

  • Zero API costs: No per-user LLM fees
  • True offline: Works in airplane mode
  • Privacy GDPR-friendly: Data never transits to servers
  • Latency: <500ms responses vs 1-3s cloud round-trips

Option 1: llama.rn (Llama Models)

The most mature React Native on-device LLM library.

Installation

Copy
npm install llama.rn
cd ios && pod install # iOS

Usage

Copy
import { initLlama } from 'llama.rn';

class LlamaService {
  constructor() {
    this.context = null;
  }

  async initialize() {
    // Model file should be in the app bundle (iOS) or app-private storage
    // (Android). RNFS.MainBundlePath is iOS-only; for Android resolve a
    // documents-directory path like the download example below.
    const modelPath = `${RNFS.MainBundlePath}/models/llama-3.2-1b-instruct-q4_k_m.gguf`;

    this.context = await initLlama({
      model: modelPath,
      use_mlock: true,
      n_ctx: 2048,
      n_gpu_layers: 99, // Use GPU on iOS/Android
    });
  }

  async generate(prompt) {
    if (!this.context) await this.initialize();
    
    return this.context.completion({
      prompt,
      n_predict: 512,
      temperature: 0.7,
    });
  }

  release() {
    this.context?.release();
  }
}

Downloading Models Programmatically

Copy
import RNFS from 'react-native-fs';

async downloadModel(url, filename, onProgress) {
  const modelPath = `${RNFS.DocumentDirectoryPath}/${filename}`;
  
  const exists = await RNFS.exists(modelPath);
  if (exists) return modelPath;

  const download = RNFS.downloadFile({
    fromUrl: url,
    toFile: modelPath,
    progressDivider: 10,
    begin: (res) => console.log('Download started', res.contentLength),
    progress: (res) => onProgress(res.bytesWritten / res.contentLength),
  });

  const result = await download.promise;
  if (result.statusCode === 200) return modelPath;
  throw new Error('Download failed');
}

Option 2: MediaPipe LLM Inference (Gemma)

Google’s MediaPipe (via Google AI Edge) supports Gemma models with GPU acceleration on both Android and iOS. There is no official React Native package, so you have two realistic paths:

  • Community bridge: packages like react-native-llm-mediapipe wrap MediaPipe’s LLM Inference task for RN. APIs vary between packages, so treat them as starting points and read the repo before adopting.
  • Your own native module: a thin Kotlin/Swift wrapper over the MediaPipe LLM Inference API (native dependency: MediaPipeTasksGenAI). It’s a day of work and removes a dependency on unmaintained bridges.

Gemma licensing: Gemma weights are not open source in the Apache/MIT sense. They ship under Google’s Gemma Terms of Use, which impose redistribution conditions — your app’s model distribution must comply with the use restrictions, you must not remove the terms, and Google can revoke the license. Read the terms before you bundle or rehost Gemma weights, especially if you serve model downloads from your own CDN.

Implementation sketch

Copy
// Pseudocode — the exact API depends on the bridge you choose.
// This mirrors the MediaPipe LlmInference options surface.
class GemmaService {
  async initialize() {
    this.llm = await createLlmInference({
      modelPath: `${RNFS.DocumentDirectoryPath}/gemma-2b-it-gpu-int4.task`,
      maxTokens: 1024,
      temperature: 0.8,
      topK: 40,
    });
  }

  async generate(prompt) {
    if (!this.llm) await this.initialize();
    return this.llm.generateResponse(prompt);
  }
}

How Do You Build a Full Chat Interface?

Copy
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, FlatList, KeyboardAvoidingView, Platform } from 'react-native';
import { LlamaService } from './services/LlamaService';

const ChatScreen = () => {
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [modelLoaded, setModelLoaded] = useState(false);
  const llamaService = new LlamaService();

  useEffect(() => {
    const init = async () => {
      try {
        await llamaService.initialize();
        setModelLoaded(true);
      } catch (e) {
        console.error('Failed to load model:', e);
      }
    };
    init();
    
    return () => llamaService.release();
  }, []);

  const sendMessage = async () => {
    if (!inputText.trim() || !modelLoaded) return;

    const userMessage = { id: Date.now(), text: inputText, sender: 'user' };
    setMessages(prev => [...prev, userMessage]);
    setInputText('');
    setIsLoading(true);

    try {
      // Build context from recent messages
      const context = messages.slice(-6).map(m => 
        `${m.sender === 'user' ? 'User' : 'Assistant'}: ${m.text}`
      ).join('\n');
      
      const prompt = `${context}\nUser: ${inputText}\nAssistant:`;
      const response = await llamaService.generate(prompt);
      
      setMessages(prev => [...prev, {
        id: Date.now() + 1,
        text: response.text?.trim() || 'No response',
        sender: 'assistant'
      }]);
    } catch (error) {
      console.error('Generation error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
      <FlatList
        data={messages}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={[styles.message, item.sender === 'user' ? styles.user : styles.ai]}>
            <Text style={styles.text}>{item.text}</Text>
          </View>
        )}
      />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          value={inputText}
          onChangeText={setInputText}
          placeholder={modelLoaded ? "Type message..." : "Loading model..."}
          editable={modelLoaded && !isLoading}
        />
        <Button title={isLoading ? "..." : "Send"} onPress={sendMessage} disabled={!modelLoaded} />
      </View>
    </KeyboardAvoidingView>
  );
};

// Styles...

How Do You Optimize Models for Mobile?

1. Use GGUF Format (Llama)

Convert models with llama.cpp:

Copy
python convert.py --outtype f16 --outfile llama-3.2-1b-instruct-f16.gguf /path/to/model
./quantize llama-3.2-1b-instruct-f16.gguf llama-3.2-1b-instruct-q4_k_m.gguf Q4_K_M

2. Progressive Loading

Download small model first, larger on demand:

Copy
const MODELS = {
  small: 'llama-3.2-1b-instruct-q2_k.gguf', // 600 MB
  medium: 'llama-3.2-1b-instruct-q4_k_m.gguf', // 900 MB
};

async function ensureModel(type) {
  const path = getPath(MODELS[type]);
  if (!(await RNFS.exists(path))) {
    await downloadModel(`https://your-cdn/models/${MODELS[type]}`, MODELS[type], console.log);
  }
  return path;
}

Performance Expectations

I don’t have rigorously controlled benchmarks for every device class, so take these community-reported figures as ballpark expectations rather than guarantees — measure on your own target hardware before making promises in your app:

ModelApprox. download sizeApprox. RAM in useTypical speed (flagship phone)Use Case
Llama 3.2 1B (Q4)~800 MB~2 GB~15-25 t/sQuick chat
Gemma 2B (int4)~1.3 GB~3 GB~10-15 t/sQuality responses
Llama 3.2 3B (Q4)~2 GB~4-5 GB~8-12 t/sComplex tasks

Realistic minimum specs (community consensus, not official):

  • Android: flagship or near-flagship SoC (Snapdragon 8-series / Tensor G3 class), 8 GB RAM
  • iOS: iPhone 13 or newer (A15 Bionic)

Budget and older devices will struggle with anything above the 1B models, and low-RAM devices may get killed by the OS during inference.


How Do You Integrate On-Device LLMs With Expo?

Both llama.rn and MediaPipe bridges contain native code, so they don’t work with Expo Go. Use a development build:

Copy
npx expo prebuild
npx expo run:ios   # or run:android

llama.rn ships an Expo config plugin (check its README for current setup details) — enable it in app.json:

Copy
{
  "plugins": ["llama.rn"]
}

If you write your own MediaPipe native module, you’ll register it via the config-plugin mechanism yourself (or add the pods/gradle deps in the ios/ and android/ folders that prebuild generates).


What Should You Consider Before Shipping to Production?

Battery Impact

Run inference in background threads with InteractionManager:

Copy
import { InteractionManager } from 'react-native';

const generate = () => {
  return new Promise((resolve) => {
    InteractionManager.runAfterInteractions(async () => {
      const result = await llamaService.generate(prompt);
      resolve(result);
    });
  });
};

App Store Compliance

  • Keep app binary < 4 GB by offering downloadable models
  • Add “AI features not available offline” disclaimer

Conclusion

On-device LLMs in React Native are viable today. Start with llama.rn for maximum compatibility, use MediaPipe (Google AI Edge) for Gemma-specific optimizations, and always download models post-install to meet app store size limits. If you need to run other TFLite models alongside your LLM, react-native-fast-tflite is a solid companion library. The privacy and cost benefits are real — I’ve had zero API bills and 100% offline functionality.

Resources:

FAQ

Can React Native apps run LLMs locally on the device?

Yes. Libraries like llama.rn, which wraps llama.cpp, run quantized Llama models directly on iOS and Android, and MediaPipe-based community bridges run Google’s Gemma models with GPU acceleration. Everything happens on the device: no API keys, no server costs, full offline operation, and complete privacy since user data never leaves the phone.

Which is better for React Native: llama.rn or MediaPipe?

llama.rn is the most mature option and works with any GGUF-quantized model, including Llama 3.2, making it the safer default for broad compatibility. The MediaPipe route suits Gemma-specific optimizations and GPU acceleration on both platforms, but there is no official React Native wrapper — you rely on community bridges or write your own small native module.

What phones can run on-device LLMs in React Native?

Community consensus points to flagship or near-flagship hardware: a Snapdragon 8-series or Tensor G3 class Android phone with 8 GB RAM, or an iPhone 13 or newer. A Llama 3.2 1B model at 4-bit quantization needs roughly 800 MB of storage and 2 GB of RAM and reaches about 15-25 tokens per second; larger 2B-3B models need more of both.

Do on-device LLM libraries work with Expo?

Not in Expo Go, because llama.rn and MediaPipe bridges contain native code. You need an Expo development build: run expo prebuild, then expo run:ios or run:android to compile the native modules. llama.rn ships an Expo config plugin you enable in app.json, while a custom MediaPipe native module registers through the config-plugin mechanism or by editing the generated native folders.

Mihir Pipermitwala

Written by Mihir Pipermitwala

Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.

More about Mihir →
Scroll down to load comments...
Related Blogs
Why Is Gemini 4 Carbon Taking So Long? What We Know

Why Is Gemini 4 Carbon Taking So Long? What We Know

Gemini 4 Carbon was teased weeks ago and still hasn't shipped while Neon launched Nov 18. 4 confirmed facts, 3 honest inferences, and how to hedge.

AI MLAI TOOLSCOMPARISON

November 29, 2026

Gemini 4 Neon: What Google's Newest Model Brings Developers

Gemini 4 Neon: What Google's Newest Model Brings Developers

Google shipped Gemini 4 Neon on Nov 18, 2026. A developer's read on its positioning, pricing, the Neon vs Carbon naming, and who should try it first.

AI MLAI TOOLSCOMPARISON

November 28, 2026

llama.cpp v1.0: Native macOS App and What It Means Locally

llama.cpp v1.0: Native macOS App and What It Means Locally

llama.cpp hit v1.0 in November 2026 with a native macOS app. Plus measured 55% faster speculative decoding on an RTX 3090, setup commands, and a verdict.

ON DEVICE LLMAI MLDEVELOPER TOOLS

November 27, 2026

GPT-6.2 Astra and Sol: What OpenAI's New Models Actually Change

GPT-6.2 Astra and Sol: What OpenAI's New Models Actually Change

OpenAI shipped GPT-6.2 Astra and Sol on Nov 17, 2026. A skeptic's read: benchmarks, API pricing, and what actually changes for coding work.

AI MLAI TOOLSCOMPARISON

November 23, 2026

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos