useTranslation
The useTranslation hook is the primary way to access translations in your components.
Import
import { useTranslation } from '@multilocale/react'
Usage
function MyComponent() {
const { t, language, Cache } = useTranslation()
return <h1>{t('hello_world')}</h1>
}
Parameters
| Parameter | Type | Description |
|---|---|---|
forcedLanguage | string (optional) | Override the detected language |
Return Value
| Property | Type | Description |
|---|---|---|
t | (key: string, fallback?: string) => string | Translate a key. Returns the translated value, the fallback, or the key itself. Also accepts Error objects. |
translate | (key: string, fallback?: string) => string | Alias for t |
language | string | The resolved language code (e.g., 'en', 'es') |
Cache | () => JSX.Element | Component that renders a <script> tag for SSR cache hydration |
MultilocaleCache | () => JSX.Element | Alias for Cache |
Language Resolution
The language is resolved in this order:
forcedLanguageparameter passed to the hookdefaultLanguageset viainit()- Browser language (from
navigator.language) - Falls back to
'en'
Translation Function
The t function handles several cases:
String Translation
const { t } = useTranslation()
t('welcome_message') // Returns translated value
t('missing_key') // Returns 'missing_key' (the key itself)
t('missing_key', 'Fallback') // Returns 'Fallback'
Error Translation
The t function also translates error messages:
try {
await someAction()
} catch (error) {
const message = t(error, 'Something went wrong')
}
When passed an Error object, it:
- Translates the error message string
- Interpolates any
error.variables(e.g.,{count}in the message) - Appends
error.cause.messageif present
Suspense
When organizationId and project are configured via init(), the hook uses React Suspense to fetch translations. The component will suspend on the first render until translations are loaded.
import { Suspense } from 'react'
function App() {
return (
<Suspense fallback={<span>Loading translations...</span>}>
<TranslatedComponent />
</Suspense>
)
}
If the fetch fails, the hook silently sets an empty dictionary for the language and renders with the fallback behavior (keys are returned as-is).
Forcing a Language
Use forcedLanguage to render a component in a specific language regardless of the global setting:
function SpanishGreeting() {
const { t } = useTranslation('es')
return <p>{t('greeting')}</p>
}