On-Device AI in React: Keeping the Editor Ahead of the Model
A completion arrives just after you rewrite the sentence. Even on-device, that suggestion is already out of date.

A completion arrives just after you rewrite the sentence. Even on-device, that suggestion is already out of date.
Removing the network trip does not remove the editor's lifecycle. The model may need downloading, the user may keep typing, and a cancelled request may finish later. We'll build a small completion editor around those moments, so ordinary editing stays usable whether native inference is ready or not.
Check the current browser API
On-device inference removes the remote inference roundtrip, not computation time. Chrome's Prompt API can run Gemini Nano on supported devices after the model is downloaded. It does not imply zero latency, universal mobile support, zero application network traffic, or automatic GDPR compliance.
Examples follow the primary sources below; they are not claims of measured production results.
Feature-detect LanguageModel; the older window.ai.languageModel examples are not the current web API. Availability states are available, downloadable, downloading, and unavailable. Check using the same language/modalities as creation. Browser versions, supported languages, storage, and hardware requirements can change; consult the Chrome documentation rather than treating a version number as sufficient.
Create a usable session from a user action
Install a compatible @types/dom-chromium-ai in the example project. Use initialPrompts for the system message. Web sampling options differ from extension APIs, so this minimal example does not assume temperature or topK support. Download progress is the browser event's normalized loaded value, not CustomEvent.detail.loaded / total. Invoke initialization from a user action; do not pretend a failed download succeeded.
// Browser-side code; use @types/dom-chromium-ai for the browser API types.
export async function completeOnDevice(
input: string,
signal: AbortSignal,
onProgress: (fraction: number) => void,
): Promise<string> {
if (!("LanguageModel" in globalThis)) {
throw new Error("This browser does not expose the Prompt API.");
}
const options = {
expectedInputs: [{ type: "text" as const, languages: ["en"] }],
expectedOutputs: [{ type: "text" as const, languages: ["en"] }],
};
const availability = await LanguageModel.availability(options);
if (availability === "unavailable") {
throw new Error("The requested model or language is unavailable on this device.");
}
signal.throwIfAborted();
// Invoke this function from a user action so model download can be authorized.
const session = await LanguageModel.create({
...options,
signal,
initialPrompts: [
{ role: "system", content: "Return only a short continuation of the supplied text." },
],
monitor(monitor) {
monitor.addEventListener("downloadprogress", (event) => {
onProgress(event.loaded);
});
},
});
try {
signal.throwIfAborted();
return await session.prompt(input, { signal });
} finally {
session.destroy();
}
}Integrate with React without stale results
Put the helper in complete-on-device.ts. This deliberately small client component requests one completion on a button click instead of silently downloading a model while typing. Editing or cancellation invalidates the request; only the active controller can publish its result or status. API errors are visible and do not disable ordinary editing. A production autocomplete needs the same invalidation around debounce timers and keyboard acceptance.
"use client";
import { useEffect, useRef, useState } from "react";
import { completeOnDevice } from "./complete-on-device";
export function CompletionEditor() {
const [text, setText] = useState("");
const [suggestion, setSuggestion] = useState("");
const [status, setStatus] = useState("Idle");
const active = useRef<AbortController | null>(null);
useEffect(() => () => {
active.current?.abort();
active.current = null;
}, []);
function cancel() {
active.current?.abort();
active.current = null;
setSuggestion("");
setStatus("Idle");
}
async function complete() {
cancel();
const controller = new AbortController();
active.current = controller;
setStatus("Initializing native model...");
try {
const result = await completeOnDevice(
text,
controller.signal,
(fraction) => {
if (active.current === controller) {
setStatus("Downloading model: " + Math.round(fraction * 100) + "%");
}
},
);
if (active.current !== controller) return;
setSuggestion(result);
setStatus("Native completion ready");
} catch (error) {
if (active.current !== controller || controller.signal.aborted) return;
console.error("Native completion failed:", error);
setStatus("Native completion failed. The editor remains usable.");
} finally {
if (active.current === controller) active.current = null;
}
}
return (
<div>
<label htmlFor="draft">Draft</label>
<textarea id="draft" value={text} onChange={(event) => {
cancel();
setText(event.target.value);
}} />
<button type="button" disabled={!text.trim()} onClick={complete}>
Complete on this device
</button>
<button type="button" onClick={cancel}>Cancel</button>
<p role="status">{status}</p>
<p>{suggestion}</p>
</div>
);
}Try editing while a completion is pending. The edit cancels the active request and clears its suggestion. If that old request still finishes, the controller identity check prevents it from replacing the new editor state. Cancellation and stale-result protection do different jobs here.
Manage context and sensitive input
Sessions hold conversation history. The current Chrome guide exposes contextUsage and contextWindow; use the installed API typings and measureContextUsage() when budgeting inputs. Older turns can be removed on overflow, and an input that cannot fit can fail with QuotaExceededError. There is no universal 1,024–4,096-token capacity. Clone sessions when isolation is required, and destroy unused sessions.
Regex masking can reduce accidental disclosure but is not complete DLP, anonymization, or a compliance boundary. Keep histories scoped to a user/task. Any cloud fallback is a different data-processing path requiring an explicit policy and user disclosure.
Measure what actually ran
A useful timing comparison needs a reproducible benchmark record. Record browser/model version, hardware, language, prompt and output lengths, cold versus warm starts, sample count, and percentile statistics. Measure download/setup time, first streamed chunk, and full completion separately. A prompt() duration is not time-to-first-token; neither is a dictionary lookup. Report debounce time separately from inference.
The embedded demo labels native completions and dictionary simulation separately. Its last-completion timing is an observation of that request, not a hardware benchmark. Model downloads are network activity even though native inference is local. The simulation demonstrates the interaction only; it is not Gemini Nano output.
The useful question is not whether the model is local, but whether the suggestion still belongs to the text on screen. Make activation explicit, discard stale results, and measure setup separately from completion. Those choices turn an inference demo into a more dependable interaction.