Skip to content

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.

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".

idle ───► loading ───► done
unavailable ◄── (no API) │
input empty ─► idle
  • idle: hook mounted, input empty or sourceLanguage === targetLanguage.
  • loading: translation in flight (~1-3s cold for a new language pair, sub-second warm).
  • done: translation complete. output is the translated text or null.
  • unavailable: API missing. Render nothing or a fallback.
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.

The hook aborts any in-flight call when inputs change or the component unmounts. You don’t need to manage AbortController directly.

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;

Source: packages/translator/src/react/index.ts.