Skip to main content

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

ParameterTypeDescription
forcedLanguagestring (optional)Override the detected language

Return Value

PropertyTypeDescription
t(key: string, fallback?: string) => stringTranslate a key. Returns the translated value, the fallback, or the key itself. Also accepts Error objects.
translate(key: string, fallback?: string) => stringAlias for t
languagestringThe resolved language code (e.g., 'en', 'es')
Cache() => JSX.ElementComponent that renders a <script> tag for SSR cache hydration
MultilocaleCache() => JSX.ElementAlias for Cache

Language Resolution

The language is resolved in this order:

  1. forcedLanguage parameter passed to the hook
  2. defaultLanguage set via init()
  3. Browser language (from navigator.language)
  4. 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:

  1. Translates the error message string
  2. Interpolates any error.variables (e.g., {count} in the message)
  3. Appends error.cause.message if 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>
}