⚡ 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.rnis real and actively maintained; MediaPipe’s LLM Inference API is real too, but there is no official@react-native-communitywrapper — 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
npm install llama.rn
cd ios && pod install # iOSUsage
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
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-mediapipewrap 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
// 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?
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:
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_M2. Progressive Loading
Download small model first, larger on demand:
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:
| Model | Approx. download size | Approx. RAM in use | Typical speed (flagship phone) | Use Case |
|---|---|---|---|---|
| Llama 3.2 1B (Q4) | ~800 MB | ~2 GB | ~15-25 t/s | Quick chat |
| Gemma 2B (int4) | ~1.3 GB | ~3 GB | ~10-15 t/s | Quality responses |
| Llama 3.2 3B (Q4) | ~2 GB | ~4-5 GB | ~8-12 t/s | Complex 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:
npx expo prebuild
npx expo run:ios # or run:androidllama.rn ships an Expo config plugin (check its README for current setup details) — enable it in app.json:
{
"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:
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:
Related Posts
- Flutter + On-Device LLM: Run Gemma and Llama Locally in Your App (2026 Guide)
- Adding an MCP Server to Your React Native Tooling - A Practical Guide
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.

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 →