Sub topic 13
Loading catalogs on demand
This chapter assumes you have react-i18next set up with an i18n instance, as in the setup chapter. It also assumes you know async/await and that your bundler (Vite or webpack) supports dynamic import().
Why catalogs should not all ship up front
If you import every catalog in resources, each visitor downloads every language. The cost grows with every locale and every feature you translate. A German user does not need the Japanese catalog.
The fix is to bundle only the fallback language and fetch the others when a user needs them. The bundler turns each dynamic import() into a separate chunk. The browser requests that chunk the first time the code runs.
Loading a catalog and switching to it
import i18n from './i18n';
export async function loadLocale(code: string) {
if (!i18n.hasResourceBundle(code, 'translation')) {
const messages = await import(`./locales/${code}.json`);
i18n.addResourceBundle(code, 'translation', messages.default);
}
await i18n.changeLanguage(code);
}The function does three things in order:
- It checks whether the catalog is already registered, so a repeat switch costs no network request.
- It imports the JSON file and registers its contents with
addResourceBundle. - It calls
changeLanguageonly after the messages exist.
The order in step 3 matters. If you call changeLanguage first, components render the key names, or the fallback text, until the chunk arrives.
Keep the initial bundle small
Initialise i18next with only the fallback language in resources. The other languages then arrive through loadLocale.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
i18n.use(initReactI18next).init({
resources: { en: { translation: en } },
lng: 'en',
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
export default i18n;Keeping English in the main bundle means a missing key in any other language still has text to fall back on. It also means the first render never waits on the network.
Common errors
- Unanalyzable import paths. Bundlers can only split a dynamic import when the path has a fixed folder and extension, such as `
./locales/${code}.json. A path built entirely at runtime, or one without the.json` extension, usually fails at build time or in the browser. - Unchecked locale codes. The
codevalue often comes from a URL or from storage. Check it against an allow-list such as yourLANGUAGESarray before importing it. An unknown code makes the import reject. - No error handling.
import()rejects when the network fails. Wrap the call intry/catch, and keep the current language if loading fails. - Racing switches. If a user changes language twice quickly, the slower request can finish last and win. Compare against the most recent request before calling
changeLanguage, or disable the selector while loading. - Loading at startup. If the saved language is not English, call
loadLocalebefore the first render, or show a loading state. Otherwise the user sees a flash of English.
Exercise
A user selects Deutsch. Your handler calls i18n.changeLanguage('de') first and then imports ./locales/de.json. What does the user see, and how do you fix it?
Show answer
Until the import finishes, components render the fallback English text, or the raw keys if the fallback is also missing. Reorder the steps: await the import, call addResourceBundle with messages.default, and only then await changeLanguage('de'). Checking hasResourceBundle first also avoids refetching a catalog that is already loaded.