useTranslation (hook)
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>
}
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.
In this tutorial you'll find some ways on how to use this useTranslation hook.
You'll also see how to use it when you need to work with multiple namespaces.
useTranslation params
Loading namespaces
// load a specific namespace
// the t function will be set to that namespace as default
const { t, i18n } = useTranslation('ns1');
t('key'); // will be looked up from namespace ns1
// load multiple namespaces
// the t function will be set to first namespace as default
const { t, i18n } = useTranslation(['ns1', 'ns2', 'ns3']);
t('key'); // will be looked up from namespace ns1
t('key', { ns: 'ns2' }); // will be looked up from namespace ns2
Overriding the i18next instance
// passing in an i18n instance
// use only if you do not like the default instance
// set by i18next.use(initReactI18next) or the I18nextProvider
import i18n from './i18n';
const { t, i18n } = useTranslation('ns1', { i18n });
Optional keyPrefix option
available in react-i18next version >= 11.12.0
depends on i18next version >= 20.6.0
// having JSON in namespace "translation" like this:
/*{
"very": {
"deeply": {
"nested": {
"key": "here"
}
}
}
}*/
// you can define a keyPrefix to be used for the resulting t function
const { t } = useTranslation('translation', { keyPrefix: 'very.deeply.nested' });
const text = t('key'); // "here"
Do not use the keyPrefix
option if you want to use keys with prefixed namespace notation:
i.e.
const { t } = useTranslation('translation', { keyPrefix: 'very.deeply.nested' });
const text = t('ns:key'); // this will not work
Optional lng option
available in react-i18next version >= 12.3.1
// you can pass a language to be used for the resulting t function
const { t } = useTranslation('translation', { lng: 'de' });
const text = t('key'); // "hier"
Not using Suspense
// additional ready will state if translations are loaded or not
const { t, i18n, ready } = useTranslation('ns1', { useSuspense: false });
Last updated