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');

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.

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

Not using Suspense you will need to handle the not ready state yourself by eg. render a loading component as long !ready . 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).

Last updated