useTranslation (hook)
The useTranslation hook: get t and i18n in function components, load namespaces, wait with Suspense, and use keyPrefix.
What it does
It gets the t function and i18n instance inside your functional component.
import React from 'react';
import { useTranslation } from 'react-i18next';
export function MyComponent() {
const { t, i18n } = useTranslation(); // not passing any namespace will use the defaultNS (by default set to 'translation')
// or const [t, i18n] = useTranslation();
return <p>{t('my translated text')}</p>
}import React from 'react';
import { useTranslation } from 'react-i18next';
export function MyComponent() {
const { t, i18n } = useTranslation(); // not passing any namespace will use the defaultNS (by default set to 'translation')
// or const [t, i18n] = useTranslation();
return <p>{t($ => $['my translated text'])}</p>
}While most of the time you only need the t function to translate your content, you can also get the i18n instance (in order to change the language).
i18n.changeLanguage('en-US');When to use?
Use the useTranslation hook inside your functional components to access the translation function or i18n instance.
useTranslation params
Loading namespaces
Overriding the i18next instance
Optional keyPrefix option
available in react-i18next version >= 11.12.0
depends on i18next version >= 20.6.0
Optional lng option
available in react-i18next version >= 12.3.1
Not using Suspense
Troubleshooting
Blank screen or "suspended while rendering, but no fallback UI was specified"? useSuspense is true by default: while translations load asynchronously (http backend, locize backend, ...), the component suspends. Either wrap it in a <Suspense fallback={...}> boundary, or set useSuspense: false and handle the ready flag as shown above. Since v17.0.10 a development-only console warning points this out when it happens.
"Rendered more hooks than during the previous render" pointing at useTranslation? This was a bug in react-i18next < 16.3 (an early return before all hooks ran when the i18next instance wasn't ready yet, typically under init/render races or React StrictMode). It is fixed in >= 16.3; upgrade instead of working around it.
Last updated
