Skip to main content

useTranslation()

The useTranslation hook returns the translated string for a text, inside a component. It is the hook behind I18nKeylessText — the component is this hook plus a fragment — so it takes the same options and resolves the text the same way.

Use it where an element will not do: a placeholder, a title, an aria-label, a string handed to another library (a markdown renderer, a navigator's tabBarLabel). Everywhere else, prefer <I18nKeylessText>.

Available since i18n-keyless-react@3.3.0.

Function Signature

// docs-check: skip — a signature listing, not a snippet to run
useTranslation(
text: string,
options?: {
context?: string;
namespace?: string;
unpersistedNamespace?: boolean;
replace?: Record<string, string>;
forceTemporary?: Record<string, string>;
originLanguage?: Lang;
debug?: boolean;
}
): string

Parameters

text

type: string (required)

The text to translate, written in your primary language. It is also the translation key.

options

type: TranslationOptions

The same options as the props of I18nKeylessTextcontext, namespace, unpersistedNamespace, replace, forceTemporary, originLanguage, debug.

Return Value

type: string

The translated text in the current language. The source text when the current language is the primary language, or while the translation has not arrived yet.

Basic Usage

import { useTranslation } from 'i18n-keyless-react';

export function SearchBox() {
const placeholder = useTranslation('Search products...');
const label = useTranslation('Search input');

return <input type="search" placeholder={placeholder} aria-label={label} />;
}

useTranslation vs getTranslation

useTranslation(text)getTranslation(text)
Whereinside a componentoutside a component: a loader, head(), a utility
Reactiveyes — re-renders when the translation lands or the language changesno — reads the store once
SSRreads <I18nKeylessProvider>, like <I18nKeylessText>reads the runWithI18nKeyless scope

Under TanStack Start the component tree renders outside the runWithI18nKeyless scope, so getTranslation() in a component body renders the primary language on the server. useTranslation is the string API that is correct there.

Notes

  • Must be called in a React component or another hook, unconditionally — the rules of hooks apply
  • Queues the text for translation on first sight, like <I18nKeylessText> does; nothing else to wire
  • Do not re-implement the lookup by reading useI18nKeyless((s) => s.translations) yourself: the storage key format, the primary-language shortcut, originLanguage and the SSR snapshot are all inside this hook