Search code examples
reactjsinternationalizationreact-i18next

react: i18n from the useTranslation vs i18n.js


I am working on a react web application using react-i18next.

Curious about the differences between accessing i18n instance from useTranslation hook vs i18n.js.

i18n.js

i18n.use(initReactI18next).init({
  whitelist: Object.keys(resources),
  resources,
  lng: "en",
  fallbackLng: "en",
  keySeparator: ".",
  interpolation: {
    escapeValue: false
  }
});

export default i18n;

I am able to changeLanguage of my application using both of this, may I know what are the differences between both i18n?

import { useTranslation } from "react-i18next";

export const Test = () => {
  const { i18n } = useTranslation();

  return <button onClick={() => i18n.changeLanguage("de")}>Change</button>;
}

vs

import i18n from "./i18n.js";

export const Test = () => {
  return <button onClick={() => i18n.changeLanguage("de")}>Change</button>;
};

I found a similar question from react-i18next - import i18n instance & use directly vs using useTranslation hook but still don't understand the differences from the provided answers (since it is about t() ).

Will it affecting performances of the application, or it is just not the practice of doing so?

Thank you.


Solution

  • In most setups, i18n is the same instance... But I would always recommend to use the i18n returned by the useTranslation hook. It will not only return the instance but also make sure the requested namespaces are loaded etc...