useTranslator
React adapter for @web-ai-sdk/translator. Auto-translates input from sourceLanguage to targetLanguage and re-runs whenever the inputs change. For the conceptual overview see Translator.
Live demo
Section titled “Live demo”Type in the source field; the translation updates whenever the text changes.
import { useTranslator } from "@web-ai-sdk/translator/react";
export function Translation({ text }: { text: string }) { const { status, output } = useTranslator({ input: text, sourceLanguage: "en", targetLanguage: "pt", });
if (status === "unavailable") return null; return <p>{output}</p>;}The hook auto-runs whenever any input changes. Empty input or matching source/target keeps the hook in "idle".
State machine
Section titled “State machine”idle ───► loading ───► done │unavailable ◄── (no API) │ ▼ input empty ─► idleidle: hook mounted, input empty orsourceLanguage === targetLanguage.loading: translation in flight (~1-3s cold for a new language pair, sub-second warm).done: translation complete.outputis the translated text ornull.unavailable: API missing. Render nothing or a fallback.
Caching
Section titled “Caching”const { output, fromCache } = useTranslator({ input: text, sourceLanguage: "en", targetLanguage: "pt", cache: "session",});fromCache is true when the cache served the result. Pass "session" / "local" for the matching web-storage shortcut, or any { get, set }-shaped object for a custom backend.
Aborting
Section titled “Aborting”The hook aborts any in-flight call when inputs change or the component unmounts. You don’t need to manage AbortController directly.
Reference
Section titled “Reference”import type { UseTranslatorOptions, UseTranslatorReturn, TranslatorStatus } from "@web-ai-sdk/translator/react";
type TranslatorStatus = "idle" | "loading" | "done" | "unavailable";
interface UseTranslatorOptions extends Omit<TranslateOptions, "signal"> { enabled?: boolean; // default: true // Inherited from TranslateOptions: input: string; sourceLanguage: string; targetLanguage?: string; monitor?: (m: TranslatorMonitor) => void; cache?: "session" | "local" | { get, set }; cacheKey?: string;}
interface UseTranslatorReturn { status: TranslatorStatus; output: string | null; error: Error | null; fromCache: boolean;}
declare const useTranslator: (options: UseTranslatorOptions) => UseTranslatorReturn;