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();// 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');
The useTranslation
hook will trigger a Suspense if not ready (eg. pending load of translation files). You can set useSuspense
to false if prefer not using Suspense.
Use the useTranslation
hook inside your functional components to access the translation function or i18n instance.
// load a specific namespace// the t function will be set to that namespace as defaultconst { 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 defaultconst { t, i18n } = useTranslation(['ns1', 'ns2', 'ns3']);t('key'); // will be looked up from namespace ns1t('ns2:key'); // will be looked up from namespace ns2
// passing in an i18n instance// use only if you do not like the default instance// set by i18next.use(initReactI18next) or the I18nextProviderimport i18n from './i18n';const { t, i18n } = useTranslation('ns1', { i18n });
// additional ready will state if translations are loaded or notconst { t, i18n, ready } = useTranslation('ns1', { useSuspense: false });
Not using Suspense you will need to handle the not ready state yourself by eg. render a loading component as long ready === false
. Not doing so will result in rendering your translations before they loaded which will cause save missing be called although translations exists (just yet not loaded).