react-brain
Menu · Topics

AI in React apps

21 readings on ai in react apps, each with our note on why it matters.The articles are the originals — read them there.

On-device AI / ML

Fitting RAG in Your Pocket: Local Retrieval in React NativeRitesh Shukla (Margelo) · margelo.com

You are building on-device RAG in React Native — memory binds before quality: generator + embedder must fit together (~900MB on a budget phone; a 1.07GB model dies on an untrappable native OOM) and query and documents need one embedding model.

The build behind this entry's react-native-rag / local-RAG option rows, done by hand so every constraint is visible: a WhatsApp export chunked, embedded and searched entirely on a $100 Android phone in airplane mode. The stack is one engine and one store — @react-native-ai/llama (llama.cpp) runs BOTH the embedder and the generator, and react-native-nitro-sqlite statically links sqlite-vec so KNN is a vec0 virtual table queried with `WHERE embedding MATCH ? AND k = ?`, no second ML runtime and nothing fetched at runtime. What makes it durable is the failure list. MEMORY IS THE CEILING, not accuracy: ~900MB usable RAM holds Qwen2.5-0.5B-Instruct Q4 (469MB) beside the 119MB embedder, and Qwen2.5-1.5B (1.07GB) hard-crashed the process with an uncatchable native OOM that JS cannot trap. The context window is paid for in KV-cache RAM, so it is capped at 4,096 tokens and a 21,000-token export is REJECTED outright ('Context is full'), not truncated — which is the whole reason retrieval exists here. Query and documents must be embedded by the same model with the same normalization, or search returns noise (the author calls this the number-one RAG pitfall). The multilingual embedder (paraphrase-multilingual-MiniLM-L12-v2, 384 dims, ~119MB at Q4) is worth its size the moment chats aren't pure English — all-MiniLM-L6 collapsed non-English messages to nearly identical vectors. Chunk boundaries are part of the data model: strip the speaker or timestamp and the model hallucinates them back. And a small model needs an explicit 'say you don't know' escape plus replayed recent turns, or follow-up questions retrieve the wrong thing entirely.

On-Device AI Beats Cloud for TTS — Here's WhyMateusz Kopciński (Software Mansion) · swmansion.com

You ship react-native-executorch — the on-device-vs-cloud TTS case (Kokoro): cost, latency and privacy favor on-device, with the tradeoffs being voice/language coverage and a custom C++ phonemizer.

A reasoned cost/latency/privacy case for on-device TTS (Kokoro via react-native-executorch), with the economics and the tradeoffs (voice/language coverage, a custom C++ phonemizer). A durable framing for the on-device-vs-cloud decision.

Edge AI in Production: What Apple, Meta, and Google Already Ship On-DeviceMartyna Szabat (Software Mansion) · swmansion.com

You're weighing on-device AI in React Native — it's production-proven at big-tech scale (Meta runs ExecuTorch inside WhatsApp/Instagram/Messenger), and small models get good enough through task-specific fine-tuning, not size.

Survey evidence that on-device AI is production-proven, not experimental: Apple ships multimodal-embedding photo search + hybrid Siri; Meta runs ExecuTorch in WhatsApp (network prediction), Instagram (SqueezeSAM cutouts) and Messenger (transcription); Google ships scam detection + Gemini Nano; Snapchat runs 10MB AR models. Ends in RN ExecuTorch pointers (Gemma/Qwen, ~30MB quantized Whisper Tiny STT) — vendor self-promotion, they author the lib. The durable framing: 'fine-tuning is what makes a small model good enough.'

Building a Real-Time Face Recognition App in React Native with VisionCameraMargelo · blog.margelo.com

You ship VisionCamera and want on-device inference — frame processors hand you each frame synchronously on a native thread, with no serialization or pixel copy; that is what makes a real-time pipeline viable (~39ms per cycle on a Galaxy S21 Ultra).

The end-to-end build this entry's option rows only imply: a fully on-device recognition pipeline — detection → tracking → alignment → embedding → matching → liveness — on VisionCamera 5 frame processors, with ONNX Runtime (CPU/XNNPACK) for inference and Reanimated shared values bridging worklet and JS. Two things make it durable knowledge rather than a tutorial. First, the architectural reason it can work at all: the frame processor gets each YUV frame synchronously on a dedicated native thread as a worklet, with no bridge serialization and no pixel copy into JS. Second, real numbers on a Galaxy S21 Ultra — YuNet detection (~230KB model) 3–6ms/frame at 128×128, SFace embedding (37MB, 19MB int8) ~29ms, ~39ms end-to-end per detection cycle, gallery matching in microseconds for 512 entries — plus the budget trick of running detection every 10th frame and letting tracking bridge the gaps. Uses ONNX Runtime rather than this entry's ExecuTorch default, which is itself a useful data point.

Generative UI & in-app AI

Respecting your users' dread of the clankersthoughtbot · thoughtbot.com

You're adding an AI feature to a product — ask for access just-in-time and per-capability (not at signup, not blanket), guard against sensitive input reaching the LLM, and give users an easy manual fallback and a way to revoke access later.

A consent-design argument for AI features: opt-in and JUST-IN-TIME, not blanket — show the specific problem the AI solves, then ask contextually ('stuck on this form?'), with granular per-capability checkboxes ('book appointments' vs 'share all health data') rather than one all-or-nothing toggle, an easy no-friction fallback to the manual workflow, guards that warn before accepting sensitive input and reject PII before it reaches the LLM, and a revocation UI showing what the AI currently can access.

Generative User Interfaces — rendering UI with language modelsVercel (AI SDK) · ai-sdk.dev

You ship the Vercel AI SDK — the generative-UI model: tools return structured JSON mapped to React component props; the client-side switch statement doesn't scale, so stream components during generation via createStreamableUI/RSC.

The core generative-UI mental model: tools return structured JSON that maps to React component props; the client-side switch-statement scaling problem; and the server-side createStreamableUI/RSC solution for streaming components during generation.

Architectural Patterns for Generative UI in Reactboda.sh (Pixelmatters Show & Tell talk, 2026-07-29) · boda.sh

You're adding generative UI — pick the architecture before the library: tool-JSON onto your component registry, declarative spec trees (A2UI/AG-UI), or sandboxed open-ended HTML; the spec layer, not the framework, is where the category is settling.

The field map above the Vercel reading's single pattern — three generative-UI architectures with working demos: (1) tool-constrained JSON mapped onto an existing component registry (Mastra + AI SDK), (2) declarative component-tree specs (A2UI v0.9) transported over the AG-UI protocol (CopilotKit demo) — native rendering with a safe payload, no arbitrary code execution, (3) open-ended LLM-emitted HTML/CSS/JS sandboxed in iframes via MCP Apps. Argues the interoperable spec layer (A2UI/AG-UI/MCP) is where the category is standardizing, over any one framework.

How to Build a Performant AI Markdown RendererTiger Abrodi · tigerabrodi.blog

You ship streaming LLM output — render markdown the Streamdown way: repair incomplete markdown before parsing, memoize at block level so every token doesn't re-parse, cache the processor, and wrap updates in startTransition.

The architecture behind streaming-markdown rendering (the Streamdown problem): repairing incomplete markdown before parsing, block-level memoization to avoid re-parsing every token, processor caching, and startTransition for smooth streaming.

Building a ChatGPT-Style AI Chat App in React Native with RAG & StreamingDave Mkpa-Eke (Margelo) · blog.margelo.com

You're building an AI chat UI in React Native — keep the JS thread free: decode streaming sockets, parse markdown, and fetch RAG natively; render the transcript with a chat-optimized list. Per-token JS-thread work is what makes streaming chat jank.

A production RN chat-app architecture (MargeloChat): stream OpenAI over WebSocket with UTF-8 decoding off the JS thread (react-native-nitro-websockets), native markdown parsing (Software Mansion's react-native-enriched-markdown), Legend List v3 for the transcript, keyboard-controller for composer tracking, true-sheet + liquid-glass for chrome, Pinecone RAG over nitro-fetch — 57-60fps by keeping every expensive step native or UI-thread. Margelo self-promotes its Nitro ecosystem throughout; the architectural principle stands independent of the vendor picks.

AI-assisted development — agent skills, MCP tooling & device automation

Reflex: an architecture for building mobile apps with agentsShopify Engineering (Thiago Magalhaes) · shopify.engineering

Your agents are slow because every check needs a simulator: make screen logic runnable headlessly behind a state/actions contract with a CLI, so agents verify behaviour without a device.

The agent-feedback-loop half of Shopify's migration: a UI-free core module that runs headlessly on macOS/JVM, an Elm-style ViewModel contract per screen (actions in, state out), JSON introspection of every ViewModel, and a platform-agnostic CLI that lets an agent load a screen, fire actions and assert state in milliseconds without a simulator. One test file runs against both iOS and Android, so neither platform can ship a feature without the other ('share the test, not the code').

A Website Can Read Your Local MCP Server, and Here's How to Stop ItSoftware Mansion · swmansion.com

You run or build a local MCP server over HTTP — loopback binding is not a security boundary: DNS rebinding lets a visited web page (or an agent's fetch tool) call it, so validate Host/Origin, require a local token, or use stdio transport.

The security caveat this entry's MCP-heavy picks never stated: binding an MCP server to 127.0.0.1 keeps other machines out but not web pages. DNS rebinding lets a page you merely visit re-resolve its own hostname to loopback after the DNS cache expires, so the browser treats requests to your local server as same-origin; the author ran the MCP handshake against an unauthenticated FastMCP server and read its config (a fake Stripe key and database URL included). Chrome and Firefox now gate public-to-loopback requests (Private/Local Network Access), but Safari 27 still let it through when re-tested in September 2026, and non-browser clients (an agent's fetch tool that only checks the URL) have no such check at all. FastMCP 4.0.10 ships a Host/Origin guard that is OFF by default. Fix on any stack: reject requests whose Host header is not a loopback name (stops every rebinding), validate Origin as the MCP Streamable HTTP spec already requires, and require a local token against a malicious local process; stdio transport avoids the network entirely (Argent uses stdio and puts a Host allowlist on its local Express tool-server). Vendor-authored, but the demo is reproducible.

Native is now the future of mobile at ShopifyMustafa Ali (Shopify Engineering) · shopify.engineering

Read here for the AGENT-WORKFLOW half of a post that is mostly famous for its framework decision (RB-E-CROSSPLATFORM owns that argument).

Two mechanisms are transferable regardless of what you think about the framework call. (1) HELIX, their migration system, exists because pointing an LLM at a codebase and asking for the same features in another language produces unshippable volume even when you freeze specs and task files first; instead a developer points it at one screen, it proposes small ordered checkpoints reviewable in minutes, and each checkpoint must prove behavior with tests, match the running app in a visual review, survive two adversarial code reviewers and get a human's nod before the next one starts — with review feedback remembered so the loop needs less hand-holding over time. The generalizable rule is that the gate, not the prompt, is what makes agent output shippable. (2) AGENT-ADDRESSABLE ARCHITECTURE: they argue the real mobile bottleneck is the FEEDBACK loop, not code generation — agents change code in seconds but take minutes to verify through a simulator, because reading state via the accessibility tree or screenshots is slow and brittle. Their fix is architectural: keep business logic fully decoupled from UI and runnable headlessly on desktop, then expose it to agents through a CLI that inspects state, navigates and acts in milliseconds, with simulator control reserved for when UI truly matters. That principle is framework-independent — it is the same reason this entry rates tools that give an agent a closed verify loop.

Helix: the internal tool powering Shopify's native migrationShopify Engineering (2026-09-21) · shopify.engineering

You port or rebuild screens with agents — Shopify's Helix swaps pixel diffing for a vision model that lists each visual difference with severity and location, scoped to what the current checkpoint built.

The primary source for the gate mechanics the back-to-native reading above only summarizes, and its most transferable part is HOW they verify UI equivalence when nobody can specify it. The four gates run in order and a failed gate cannot be overridden by the agent. Gate 1 (behavior): a CLI exposes the same screen state and actions as the app, so tests run without a simulator and the agent can iterate dozens of times before taking a single screenshot; a subagent generates per-checkpoint integration tests from the reference code, and those tests define what 'proven' means. Gate 2 (UI review) is the one they credit for near-1:1 output: pixel diffing is rejected because two UI frameworks never produce identical bytes, so an orchestrator (GPT) captures matching-state screenshots of reference and new app and asks Gemini — chosen for its spatial awareness — to act as a perfectionist design reviewer that must list every difference with a severity and an on-screen location, judged proportionally to each screenshot's dimensions; fixable differences are blockers by default, the reviewer can return INVALID when the two screenshots show different states (the orchestrator then re-captures), and review scope grows with each checkpoint (a skeleton checkpoint is checked only for nav bar and title). Gate 3: two independent, context-isolated reviewer agents check the new code against the documented target architecture and every finding must be fixed. Vendor-side account of their own process: no acceptance rates or timings are given.

3 Minutes With an Agent, 9 Seconds on ReplayMichał Pierzchala (Callstack) · callstack.com

You have an agent driving simulators or devices — the model, not the device, is the cost: a nine-action flow took 3m18s live and 8.8s on replay with zero model calls. Discover a flow once with the model, then replay it deterministically.

Measures where the time actually goes when an agent drives a device, and the answer is: not on the device. A nine-action QA task on an Android emulator took the agent 3m18s; saved as a replayable script and re-run with `agent-device replay` it finished in 8.8 seconds INCLUDING app launch, with zero model calls. Taps and snapshots were thin slices of the original run — the ~190-second gap is model inference, API round trips, screen reading and deciding what to do next. Two numbers make it actionable: in the opening run 2 of 29 tool calls were help lookups or rejected commands, and across an audit of 108 spontaneous runs 375 of 2,668 calls (14.1%) never reached the device at all. So the design rule for agent-driven device work is to spend model turns on DISCOVERING a flow once, then replay it deterministically for every repeat — the same split that makes recorded E2E cheap. Stated caveats: simulators/emulators on a workstation (no physical devices), load-gated timings for one experiment only, small + mid-tier models of one provider.

Testing Google's modern-web-guidance skill against a real React appAlfy · alfy.blog

Your agent writes frontend code that was best practice three years ago — consult a curated guidance index (modern-web-guidance) before writing rather than reviewing after. It never reads your code: you still inventory, query, and judge whether a rule applies.

An independent field test of the option row above, and the honest scoping this category usually lacks. Pointed at a real Vite + React questionnaire app (42 files) it correctly flagged a hardcoded light theme with no color-scheme/prefers-color-scheme, data-entry surfaces with zero <form> elements, validation predating :user-invalid, and min-height:100vh where 100dvh is the modern answer — each with Baseline-checked, copy-pasteable guidance, and it also explicitly endorsed what the app already had right (fieldset/legend, role=alert, :focus-visible). The limits are the useful part: THE SKILL DOES NOT READ YOUR CODE — a human or an agent must inventory the codebase, turn each suspicion into a search phrase and compare the answer back to the actual lines; semantic search has a recall ceiling (dark-mode hit 0.75, but the dvh answer never surfaced as its own result, only inside broad omnibus guides); guides are large (forms ~4,500 tokens, accessibility ~7,100, both reported up front so you can weigh the fetch); and it returns general rules that may not apply — most of the input-attribute advice was irrelevant to a radio-driven form, and noticing that is the human's job. The author's reframe is the durable one: it is less a tool you run than a standard you consult, best used the moment BEFORE writing a component, when the model in the loop (human or AI) is about to reach for the pattern it already knows.

Bun is being rewritten in RustJarred Sumner (Bun) · bun.com

The largest published agent-driven port to date, and the methodology reading for agent fleets: Bun v1.4 ships a Zig→Rust rewrite of 535,496 lines executed by ~64 parallel Claude agents across 4 worktrees in ~50 workflows over 11 days (2026-05), ~$165k in API cost vs an estimated blocked engineer-year — with the load-bearing discipline that each implementer agent was paired with TWO adversarial reviewers in separate context windows told to assume the code was wrong.

Results: every instrumentable memory leak resolved (one bundler workload: 609MB stable vs 6.7GB before), ~20% smaller binaries, 2–5% faster. Not RN-specific, but the concrete data point for what adversarially-reviewed agent fleets can do to a production codebase — the review-pairing pattern transfers to any repo using the tools in this entry.

How Expensify Uses Agent-Device for Mobile Bug Evidence and ProfilingCallstack (with Expensify) · callstack.com

The first named production-adopter case study for agent-device: agents run Sentry-span measurement loops across branches and drive the React profiler mid-session via react-devtools integration, returning named components and render counts as bug evidence.

What agent-in-the-debug-loop looks like at a real company, beyond vendor demos.

Metrognome — An AI Agent for Measured React Native Performance FixesCallstack · callstack.com

You point an agent at performance work — require it to measure N times against a noise floor and reject its own changes that don't beat it; an agent that only reports a diff has no way to tell an optimization from a coincidence.

The layer ABOVE the device-drivers in this entry: not another profiler or benchmark, but a loop that decides what to keep. For a given performance goal it proposes one hypothesis, runs the experiment, measures it N times on a live app, keeps the change only if it beats the noise, commits it with the evidence, then picks the next hypothesis — one variable at a time. It ships no profiler and no device driver of its own; it orchestrates the tools already listed here (Agent Device for eyes and hands, Agent React DevTools, and the rest of Callstack's stack) and contributes the research loop plus memory. VENDOR POST — nearly every organ carries a Callstack logo, and the numbers are theirs. The durable, transferable part is the discipline: an optimization agent that can REJECT its own work against a noise floor is a different thing from one that reports a diff.

Meet Argent: Agentic Toolkit to Control, Debug and Profile iOS applicationsKacper Kapuściak (Software Mansion) · swmansion.com

The clearest articulation of the closed loop this entry is about: the agent that writes the code also boots the simulator, drives the UI, attaches a debugger, and profiles React+iOS in the same session — with production numbers (~50% re-render reduction in a banking app) rather than demos.

Fable 5 vs GPT-5.6 Sol: I spent $2,000 and 2 billion tokens to find out who winsRami Maalouf (Expo) · expo.dev

You drive coding agents against an RN/Expo app — budget for the validation loop, not generation: per-feature on-simulator verification dominates token spend and is what makes one-shot quality possible; pick the model on measured cost-vs-speed, not vibes.

First-party measured model comparison on real Expo apps: three models (Fable 5/Claude Code, GPT-5.6 Sol/Codex, GPT-5.5 control) each one-shot three apps end-to-end — ideation, per-feature on-simulator validation, debugging — under the same spec-driven prompt and template. Fable 5 won code + UI quality (code-health 88 vs 79/79) at ~3× the hourly cost ($74/h vs ~$30/h) and ~30% less wall-clock; the dominant token cost across all models was the simulator-validation loop, not generation. The model numbers are point-in-time (2026-08-05); the durable part is the harness — standing quality bars plus per-feature simulator validation is what made one-shot apps work at all. (Fetched via browser-UA curl; expo.dev/blog no longer blocks it.)

React Agentic Engineering 2026: The Tools Started Shipping Their Own InstructionsSascha Brandt (saschb2b.com) · saschb2b.com

You write agent context for React tooling — check what the tool already ships first: Next.js, MUI, Storybook and Playwright bundle their own MCP servers/docs/agents, which version with the package where hand-written summaries go stale.

A factual survey (with advocacy framing) of the convergence the tools themselves shipped in 2026: Next.js bundles its docs in the package (node_modules/next/dist/docs/) plus AGENTS.md and an MCP server at /_next/mcp; Material UI ships @mui/mcp and per-skill AGENTS.md; Storybook ships @storybook/addon-mcp (verified vs npm — localhost:6006/mcp, three toolsets); Playwright generates planner/generator/healer agents via `npx playwright init-agents`; Vercel publishes a react-best-practices skill installable via `npx skills add`. The durable observation: four independent teams converged on machine-readable instructions shipped WITH the tool inside twelve months — check what a library already ships before writing your own agent context for it.