Sub topic 4
Setting up react-i18next
This chapter wires i18next and react-i18next into a React app. It assumes you can write React function components with hooks, read TypeScript, and use npm with a bundler such as Vite. It also assumes you know what a message catalog and a locale identifier are from the earlier chapters. By the end you will have a working i18n instance, know what each init option does, and be able to diagnose the usual setup failures.
Two libraries, two jobs
Two packages work together here, and each has a separate role.
- i18next is the framework-independent engine. It stores catalogs, resolves a key to a string for the active language, applies fallbacks, and handles interpolation and plural suffixes.
- react-i18next is the React binding. It provides the
initReactI18nextplugin, theuseTranslationhook, and theTranscomponent. It also re-renders components when the language changes.
Install both:
npm install i18next react-i18nextreact-i18next declares i18next as a peer dependency, so keep the two on compatible major versions. A mismatch is a common source of confusing type errors.
The initialisation module
Put all configuration in one module, for example src/i18n.ts. Other files import the configured instance and never create their own.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resources = {
en: {
translation: {
greeting: 'Hello, {{name}}!',
items_one: '{{count}} item in your cart',
items_other: '{{count}} items in your cart',
},
},
de: {
translation: {
greeting: 'Hallo, {{name}}!',
items_one: '{{count}} Artikel in Ihrem Warenkorb',
items_other: '{{count}} Artikel in Ihrem Warenkorb',
},
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'en',
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
export default i18n;The default export of i18next is a global singleton instance. use(initReactI18next) registers the React plugin on it, and init applies the options. The plugin stores the instance so that hooks anywhere in the tree can find it.
The shape of `resources`
The resources object has three levels: language, then namespace, then key.
resources[language][namespace][key]In the example the language codes are en and de, and the namespace is translation. That is the default namespace. A namespace is a named group of messages. Later chapters use namespaces to split a large catalog into several files, but for now one namespace is enough. If you call t('greeting') with no namespace, i18next looks in translation.
The keys items_one and items_other use plural suffixes. You never write the suffix in code. You call t('items', { count }), and i18next picks the suffix with Intl.PluralRules. The plurals chapter covers this in depth. Here, just note that {{count}} is a reserved variable name that triggers plural lookup.
The options that matter
| Option | What it does | Notes |
|---|---|---|
| `resources` | In-memory catalogs | Fine for small apps. Larger apps load catalogs on demand. |
| `lng` | The language to start with | Omit it when you use a language detector, described in a later chapter. |
| `fallbackLng` | Language used when a key is missing in the active one | Can be a string, an array, or a map from language to fallback list. |
| `interpolation.escapeValue` | Whether i18next HTML-escapes interpolated values | React already escapes rendered values, so `false` avoids double escaping. |
| `defaultNS` | Namespace used when none is given | Defaults to `translation`. |
| `debug` | Logs lookups, missing keys and language changes to the console | Turn it on while setting up and off in production. |
Fallback in practice
Suppose the active language is de and the key greeting exists only in en. Without a fallback, t('greeting') returns the key itself, the string greeting. With fallbackLng: 'en', it returns the English text. A visible English sentence is a smaller failure than a raw key, but it is still a bug. The key management chapter shows how to catch such gaps before release.
Region subtags also fall back. If the active language is de-AT and you only provide de, i18next tries de-AT first, then de, then the fallback language. You rarely need a separate de-AT catalog unless the wording really differs.
Loading the module before the app renders
The init module must run before any component calls useTranslation. The simplest approach is a side-effect import in the entry file, placed before the root component:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './i18n';
import { App } from './App';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);The import './i18n' line has no binding. It exists only so the module executes once, which registers the instance with react-i18next. No provider component is required in the default setup, because the plugin makes the instance globally available. If you need several independent instances, for example in tests or micro-frontends, wrap part of the tree in I18nextProvider and pass the instance explicitly.
What happens at start-up
The last branch explains a symptom you will see often. When a key is missing everywhere, i18next returns the key as the output text. A screen that shows greeting instead of Hello, Ada! means the lookup failed, not that the component is broken.
A first translated component
Here is a component using the setup above. The next chapters explain the hook and variables in detail, so treat this as a check that your setup works.
import { useTranslation } from 'react-i18next';
export function Cart({ name, count }: { name: string; count: number }) {
const { t } = useTranslation();
return (
<section>
<h1>{t('greeting', { name })}</h1>
<p>{t('items', { count })}</p>
</section>
);
}With lng: 'en', <Cart name="Ada" count={1} /> renders "Hello, Ada!" and "1 item in your cart". With count={3} it renders "3 items in your cart".
Typing your keys
Plain t('greting') compiles even though the key has a typo. Recent versions of i18next let you describe your resources to TypeScript so that unknown keys are compile errors. Declare the resources as const, export them, and augment the library's CustomTypeOptions interface:
// src/i18next.d.ts
import 'i18next';
import type { resources } from './i18n';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'translation';
resources: (typeof resources)['en'];
}
}For this to work, i18n.ts must declare export const resources = { ... } as const;. The English catalog is the usual source of truth for types, because translators add other languages to match it. This also gives editor autocomplete for keys and checks that interpolation variables are the right type.
Common setup errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Keys appear instead of text | `./i18n` never imported, or imported after the component runs | Import it first in the entry file. |
| Console warning about passing an i18next instance | `initReactI18next` was not added with `use` | Call `i18n.use(initReactI18next)` before `init`. |
| Text appears in English only | `lng` is hard-coded, or the language code does not match a key in `resources` | Check the spelling and case of the code, for example `de` and not `DE`. |
| A component suspends or renders nothing at first | Resources load asynchronously, for example from a backend | Wrap the tree in `Suspense`, or read `ready` from `useTranslation`. |
| Two languages appear to mix | Several i18next instances were created | Export a single instance and import it everywhere. |
| `{{name}}` is shown literally | The variable was not passed to `t` | Pass `{ name }` as the second argument. |
When a lookup misbehaves, set debug: true and read the console. i18next logs the active language, the namespace it searched, and each missing key.
Things to keep in mind
- Initialise once, in one module, and import that module for its side effect.
- Keep
fallbackLngset so a missing translation shows readable text, and treat any fallback seen in testing as a defect. - The
resourcesapproach bundles every language into your JavaScript. That is acceptable for two or three small catalogs. The lazy loading chapter replaces it once catalogs grow.
Exercise
Your entry file imports App first and ./i18n second. Components render the raw key greeting instead of "Hello, Ada!". Give the most likely cause and the fix, and name one other check you could make using an init option.
Show answer
The init module runs after App and its imports have been evaluated, so useTranslation has no configured instance when components first call t, and i18next returns the key as the output. Fix it by importing ./i18n before App in the entry file (or importing it at the top of App itself). To confirm, set debug: true in init and read the console output. It logs the active language and each key it cannot find.
Exercise
A user's browser reports de-AT, and your resources contain only en and de. With fallbackLng: 'en', which catalog supplies the text for a key that exists in both, and why?
Show answer
The de catalog. i18next resolves de-AT first, then its base language de, and only then the fallback language en. A key present in de is found at the second step, so the fallback is never used.