3
votes

I have a project written in React & support hooks. I'm trying to use react-i18next to support translations. Everything works well as I've follow the documentation.

However I stumble upon some problems when I want to use the t() function on helpers / non-component .js files. Then, I solved it by importing i18n directly from the init file ./i18n.ts that looks something like this

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next) 
  .init({
    resources,

    ns: [
      'common',
      'dashboard',
      'landing'
    ],
    defaultNS: 'common',

    fallbackLng: 'en',
    supportedLngs: ['de', 'en'],
    interpolation: {
      escapeValue: false, 
    },
  });

export default i18n;

and I realized that I don't have to use the hook at all since I can just use it like this anywehre across the code, even on my functional component file

import i18n from "@root/i18n"

...
i18n.t('namespace:path')

I would like to know why is it recommended to use the useTranslation hook / withTranslation HOC if you can just import it like this? I read that useTranslation apply suspense but it seems like the initReactI18next also have suspense applied by default.

I'm curious on if there's any side-effect on not using the recommended hook / HOC ?

1

1 Answers

1
votes

I found this answer on their github issues.

But those constants never will be updated on languageChange! So either:

update them to new language value based on event triggered by i18next: https://www.i18next.com/overview/api#onlanguagechanged
or better have only the keys in the constants and translate as close to the rendering as possible