Skip to content
codmaker

How to Add AI to a React Native App (Step by Step)

Add AI to a React Native app the safe way: keep API keys on your backend, stream responses to the UI, send camera photos, and handle errors and cost.

Codmaker8 min read
Share

How Do You Add AI to a React Native App?

Put a small backend between your app and the AI provider. The app sends the user's text or photo to your endpoint, your server adds the API key and calls the model, and the answer streams back to the screen. Never ship the API key inside the app.

That is the whole architecture. The rest of this guide walks through each step in order: the backend, the request, streaming, images, failure states, cost and testing. It works the same in Expo and in bare React Native, and we call out the differences where they exist.

Step 1: Where Do API Keys Go? On Your Backend, Not in the App

Anything you bundle into a mobile app can be extracted. An app binary is a file on the user's phone. People unpack it, read the JavaScript bundle, and watch its network traffic. A key in your code is a key in public.

Environment variables do not fix this. In Expo, any variable prefixed with EXPO_PUBLIC_ is inlined into the bundle at build time. It is handy for a public API URL and wrong for a secret. Obfuscation only slows a curious person down.

A leaked key means strangers spend your money until you notice and rotate it. And rotating a key that lives in a shipped app means pushing an update and waiting for users to install it. Keep the key on a server and this problem goes away. So the first thing to build is that server.

Build one endpoint, for example POST /api/chat. It accepts the user's message, checks who is calling, calls the AI provider with the secret key, and returns the result. Any stack works: a Next.js route handler, Express, Hono, FastAPI or a serverless function.

Expo Router also supports API routes, so you can keep the endpoint in the same project as the app and deploy it to a host.

Authenticate the caller. If your app has sign-in, send the user's session token and verify it on the server. Without that, anyone who finds the endpoint can use it as a free proxy to your AI account.

Keep the prompt on the server too. The app sends raw user input, and the server wraps it in your system prompt and picks the model. You can then fix a prompt or switch to the latest model without shipping an app update.

  • The app sends user input and a session token to your endpoint
  • The server verifies the user and checks their usage limit
  • The server builds the prompt and calls the provider with the secret key
  • The server streams the answer back to the app

Step 2: How Do You Stream AI Responses in React Native?

Streaming shows words as the model writes them. Total time stays the same, but the user sees progress right away, which matters more on a phone than anywhere else.

On the server, turn on the provider's streaming option and forward the chunks as they arrive, either as plain text chunks or as server-sent events.

On the client, the right tool depends on your setup. The fetch built into React Native has historically not exposed a readable response body, so reading a stream from it fails. Expo ships its own implementation: import fetch from expo/fetch, call it, then read response.body.getReader() in a loop and decode each chunk with a TextDecoder. Recent Expo SDKs also install it as the global fetch, so check the docs for the SDK you are on. Another route is a server-sent events client such as react-native-sse, which is the approach our production patterns guide prefers.

Do not call setState for every chunk. A long answer can arrive as hundreds of small pieces, and re-rendering on each one makes the UI stutter. Collect chunks in a ref and flush them to state on a short timer. Model the request as a small state machine: idle, connecting, streaming, done, error.

Give the user a stop button. Create an AbortController, pass its signal to the request, and abort when they tap stop or leave the screen. That saves tokens as well as patience.

Step 3: How Do You Send Camera Photos to an AI Model?

Vision features follow the same path as text: the app captures, your backend calls the model. In Expo, expo-image-picker opens the camera or the photo library and returns a local file URI. Use expo-camera when you want a custom camera screen. Both need permission strings in your app config, and you should ask for permission at the moment the user taps the camera button.

Shrink the photo before you upload it. Camera photos are far larger than a vision model needs. Resize and compress with expo-image-manipulator, then upload the smaller file. Uploads finish faster on mobile networks and you pay for fewer image tokens.

Send the file to your backend as multipart form data, or as a base64 string for small images. The server forwards it to a vision-capable model with your prompt and returns structured data the app can render.

PlantDoc, our AI plant identifier, works this way. As described in our production patterns guide, it downsamples and JPEG-compresses each photo on the device before upload, then sends it to our backend for species identification. Tell users what leaves the device, and declare it in your App Store and Play Store privacy details.

Step 4: How Do You Handle Loading, Error and Offline States?

Mobile networks drop. Design the unhappy paths first, because your users will meet them on day one.

Check connectivity before sending, with expo-network or the NetInfo community package. If the device is offline, say so and keep what the user typed. Never clear the input until the request succeeds.

  • Loading: show a typing indicator or skeleton at once, before the first chunk arrives
  • Timeout: abort requests that hang and offer a retry button
  • Retry: retry network failures with a growing delay, but do not auto-retry a request that already streamed part of an answer
  • Partial answers: if the stream breaks midway, keep the text you have and mark it incomplete
  • Rate limited: when your server returns 429, show a clear message, not a generic error
  • Offline: disable the send button, explain why, and keep the draft
  • Refusals and empty output: handle the case where the model returns nothing useful

Step 5: How Do You Control AI Cost and Rate Limits?

Every AI call costs money, and a mobile app puts that button in every user's pocket. Set limits on your server before launch. Client-side limits are easy to bypass.

Count requests per user and reject calls over the limit. Cap the input length and the maximum output tokens for each request. Use a smaller, cheaper model for simple tasks and save the large one for hard cases. Cache answers for repeated inputs. Check your provider's pricing page and work out what one active user costs you per day.

Match limits to your business model. PlantDoc uses a free tier with limited daily identifications plus a subscription that removes the cap. Also set a spending alert in your provider's dashboard, so a bug or an abuser cannot run up a bill overnight.

On-Device AI vs Cloud AI in React Native: Which Should You Use?

Start with cloud. It works with any model, needs no native code, and runs in Expo without extra setup. Everything above this section is the cloud path.

On-device models run on the phone itself. They work offline, keep data private, and cost nothing per call. In exchange you get smaller models, larger app downloads, native modules, and performance that varies from phone to phone. In Expo that means a development build, since Expo Go cannot load custom native code.

A hybrid setup uses both: a small local model for instant feedback and the cloud for the real answer. Move to on-device or hybrid when you have a concrete reason, such as offline use, privacy rules or a per-call cost you cannot carry.

Step 6: How Do You Test AI Features in a React Native App?

AI output changes from run to run, so split your tests in two. Test your app logic against fake responses, and test model quality on the server.

For the app, mock your endpoint. Feed the streaming hook a scripted series of chunks and check each state: connecting, streaming, done, error, aborted. Simulate a dropped connection halfway through a stream. These tests are fast and never flake.

For the model, keep a small set of real inputs with the results you expect, and run it on the server whenever you change the prompt or the model. Then test by hand on real devices. Use an older Android phone on a slow connection, switch on airplane mode mid-request, and deny the camera permission. The simulator hides most of what breaks in the field.

Frequently Asked Questions

Can I call the OpenAI or Claude API directly from a React Native app?

Technically yes, but you should not. The API key would ship inside the app, where anyone can extract it and spend your credit. Call your own backend and let the server hold the key.

Does fetch support streaming in React Native?

The fetch built into React Native has not traditionally exposed a readable response body. Expo provides a streaming-capable fetch in expo/fetch, and server-sent events libraries are another option. Check the docs for the React Native and Expo versions you use.

Can I add AI to an Expo app without ejecting?

Yes. Cloud AI needs only network requests, so it runs in a standard Expo project, including the camera and image picker modules. You need a development build only when you add libraries with custom native code, such as on-device inference runtimes.

How much does it cost to add AI to a mobile app?

It depends on the model, the length of each request and how often people use the feature. Estimate the cost of one typical request from your provider's pricing page and multiply by expected daily use. Per-user limits, caching and smaller models keep the number under control.

Should I run AI on-device or in the cloud?

Start in the cloud. It is simpler, supports the most capable models and works in Expo out of the box. Move to on-device when you need offline use, stronger privacy or no per-call cost.

Written by Codmaker

An independent product lab. We build and run our own React Native and Next.js apps, and write up what we learn along the way.

See our apps
All guides →