useTranslation() Hook

Learn how to access the translation function or i18n instance inside function components.

We'll cover the following

Hooks in withTranslation()

The use of the withTranslation() HOC is not constrained to class components but can also be used in function components. However, using the useTranslation() Hook often simplifies the component and makes it much more readable. The Hook can be imported similarly to the HOC:

import { useTranslation } from 'react-i18next';

The useTranslation() Hook allows us to extract the t and i18n properties by using destructuring assignment from ES2015+:

const Greeting = () => {
  const { t, i18n } = useTranslation();
  return (
    <div>
      <p>{t('greeting')}</p>
      <button onClick={() => i18n.changeLanguage('de')}>de</button>
      <button onClick={() => i18n.changeLanguage('en')}>en</button>
    </div>
  );
};

As was already the case in the withTranslation() HOC, t refers to the function that allows us to display translations based on their translation key. i18n refers to the respective i18next instance. The useTranslation() Hook offers the same set of functionality as the withTranslation() HOC, but the ‘useTranslation()` is much more explicit and thus more readable. In order to use different namespaces, we can pass a string or an array of strings containing the namespaces to the Hook:

const { t } = useTranslation('namespace');
const { t } = useTranslation(['namespace1', 'namespace2']);

If no namespace has been provided, the default settings will be used.

Run the code snippet below to visualize all these functionalities interactively:

Get hands-on with 1200+ tech skills courses.