Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Add ChatGPT-style AI chat to your Expo app in 5 minutes

Almost every app wants an "Ask AI" screen now. Building one in React Native sounds easy until you hit the details: Text stutters while the response streams in, token by token Half-written markdown (**bold, an unclosed

Add ChatGPT-style AI chat to your Expo app in 5 minutes

Almost every app wants an "Ask AI" screen now. Building one in React Native sounds easy until you hit the details:

  • Text stutters while the response streams in, token by token
  • Half-written markdown (**bold, an unclosed code block) breaks the layout
  • fetch in React Native doesn't stream response bodies out of the box
  • The keyboard covers the input on Android
  • Then come stop, retry, chat history, file uploads...

I rebuilt these one too many times, so I packaged them as an open-source library: react-native-ai-chat-kit. Here's how to add a full AI chat to an Expo app.

Four screens of the chat kit: a tool card and table, an optimized photo upload, chat history, and a custom purple theme

1. Create the app and install

npx create-expo-app@latest my-ai-app --template blank-typescript
cd my-ai-app
npx expo install react-native-ai-chat-kit react-native-safe-area-context

The kit is pure TypeScript with no native code, so it runs in Expo Go and in React Native CLI apps.

2. A working chat, no API key needed

Replace App.tsx:

import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import { ChatView, createMockTransport, useChat } from 'react-native-ai-chat-kit';

const transport = createMockTransport(); // a fake AI that streams demo answers

export default function App() {
  const chat = useChat({ transport });
  return (
    <SafeAreaProvider>
      <SafeAreaView style={{ flex: 1 }}>
        <ChatView {...chat} suggestions={['What can you render?', 'Plan a trip to Goa']} />
      </SafeAreaView>
    </SafeAreaProvider>
  );
}

Run npx expo start and open it in Expo Go. Tap a suggestion and watch a reply stream in with markdown, a table and a tool-call card. Stop, Retry and Copy already work.

3. Connect a real model

Swap the mock for a provider. It's three lines:

import { createProviderTransport } from 'react-native-ai-chat-kit';

const transport = createProviderTransport({
  provider: 'anthropic', // or 'openai' | 'gemini'
  apiKey: process.env.EXPO_PUBLIC_AI_KEY!,
  model: 'claude-sonnet-5-5',
  system: 'You are a friendly travel assistant.',
});

It also works with any OpenAI-compatible API (OpenRouter, Groq, Ollama...) through baseUrl.

Never ship an API key inside an app. Anyone can pull it out of the bundle and spend your money. That's why createProviderTransport refuses to run in production builds. It's for prototyping. Step 4 is for real apps.

4. Go to production with the built-in server

The package includes a server handler that keeps the key on your server. With Next.js on Vercel, it's one file:

// app/api/chat/route.ts
import { createChatHandlerFromEnv } from 'react-native-ai-chat-kit/server';

const handler = createChatHandlerFromEnv(process.env);
export const POST = handler;
export const OPTIONS = handler;

Set AI_PROVIDER, AI_API_KEY and AI_MODEL in your Vercel project settings, then point the app at it:

const transport = createStreamTransport({ url: 'https://your-app.vercel.app/api/chat' });

Switching from OpenAI to Claude is now a settings change. Templates for Cloudflare Workers and plain Node are in the repo.

5. Add chat history

Swap useChat for useChatSessions and every conversation is saved. Users can reopen any chat and keep talking, with its full context:

import AsyncStorage from '@react-native-async-storage/async-storage';
import { ChatHistory, createKeyValueStore, useChatSessions } from 'react-native-ai-chat-kit';

const store = createKeyValueStore(AsyncStorage);

const chat = useChatSessions({ transport, store, restoreLastSession: true, maxAgeDays: 30 });

// A ChatGPT-style list: Today, Yesterday, Previous 7 days... with search and delete
<ChatHistory
  sessions={chat.sessions}
  activeSessionId={chat.activeSessionId}
  onSelect={chat.openSession}
  onDelete={chat.deleteSession}
  onNewChat={chat.newSession}
/>

6. Photos, documents and voice

npx expo install expo-image-picker expo-document-picker expo-image-manipulator expo-speech
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'expo-document-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import * as Speech from 'expo-speech';
import { createExpoAttachmentPickers, createExpoSpeech } from 'react-native-ai-chat-kit';

const attachments = createExpoAttachmentPickers({ ImagePicker, DocumentPicker, ImageManipulator });
const speech = createExpoSpeech(Speech);

<ChatView {...chat} attachments={attachments} speech={speech} />

Photos are resized to 1568px and compressed before upload, so a 4 MB photo becomes roughly 300 KB. PDFs go to the model as files, and text files are read in as text. Each reply gets a Listen button. For speech-to-text, add expo-speech-recognition (it needs a development build) and pass voice={createExpoSpeechRecognizer(ExpoSpeechRecognitionModule)}.

7. Make it yours

<ChatView
  {...chat}
  theme={{ colors: { accent: '#7C3AED', userBubble: '#7C3AED', userText: '#fff' }, fontFamily: 'Inter-Regular', radius: 8 }}
  renderAvatar={(m) => (m.role === 'assistant' ? <BotAvatar /> : null)}
  renderToolCall={(part) => (part.name === 'search_flights' ? <FlightCard data={part.result} /> : undefined)}
/>

Colors, fonts, every bubble and button, tool-call cards and history rows can all be swapped.

How the streaming stays smooth

For the curious, three things do most of the work:

  1. One render per frame, not per token. Incoming tokens are buffered and applied once per animation frame.
  2. Memoized markdown blocks. Finished paragraphs, tables and code blocks never re-render. Only the block still receiving tokens does.
  3. A parser built for half-written text. An unclosed **bold renders bold instead of flashing asterisks, and an unfinished code block renders as an open code block.

Streaming itself uses XMLHttpRequest progress events, which deliver text incrementally on iOS, Android and web without polyfills.

Try it

It's MIT licensed and at v0.1, so I'd love your feedback. What would you need before using it in production? Issues and stars are both very welcome.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.