Sub topic 13
Loading catalogs on demand
This chapter assumes you can write React function components and hooks, use async/await and ES modules, and run a Vite or webpack project. It also assumes you have react-i18next set up as in the earlier chapters, with i18n.changeLanguage already wired to a language switcher.
Why catalogs should not ship in the main bundle
The setup in the earlier chapters imports every catalog into resources. That works for two languages and a few dozen keys. A real app may support 20 locales with thousands of messages each. If all of them sit in the main bundle, every visitor downloads text in languages they will never read.
A visitor needs one catalog at a time: the active locale, plus the fallback locale when a key is missing. Loading on demand means the initial bundle contains only the fallback catalog. Other catalogs are separate files that the browser fetches when the user first selects that locale.
The trade-off is a delay. Switching to German now involves a network request, so the UI must handle the time between "the user asked for German" and "German is ready".
Dynamic import creates one chunk per locale
A dynamic import() call tells the bundler to put the imported module in its own file and fetch it when the call runs. Vite and webpack both do this. When the path is a template literal such as ` ./locales/${code}.json `, the bundler finds every file that could match and builds one chunk for each.
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:
hasResourceBundlechecks whether the catalog is already registered. On a repeat visit to the same locale, this skips the network request.addResourceBundleregisters the loaded messages under the locale and thetranslationnamespace. The.defaultproperty holds the JSON content, because the bundler wraps JSON modules as ES modules.changeLanguageswitches the active language only after the messages exist. If you switched first, the UI would briefly render raw keys or fallback text.
The order matters. Registering the bundle before the switch means React never renders the new locale without its messages.
Keep the glob narrow
The bundler decides which files to chunk from the static part of the path. In ./locales/${code}.json, the directory and the .json extension are fixed, so only files directly in locales/ ending in .json are included. Avoid a path like ` ./${code} `. It makes the bundler pull in far more files than you intend.
Keep only catalog files in that directory. A stray README.json or test fixture would be bundled too, and code could in theory request it.
Initialising with only the fallback locale
The fallback catalog has to be available synchronously, so it stays in the initial bundle. Reduce resources to that one catalog:
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;The static import en keeps English in the main chunk. Every other locale is fetched through loadLocale. Because the fallback is always loaded, a missing key in German falls back to English text instead of showing the key name.
The startup case: a returning user who prefers German
If the user's saved or detected locale is not the fallback, you have a timing problem. The app should not render in English and then flip to German a moment later. Load the catalog before the first render:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { loadLocale } from './loadLocale';
const saved = localStorage.getItem('locale') ?? 'en';
loadLocale(saved)
.catch(() => loadLocale('en'))
.finally(() => {
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
);
});If the request for the saved locale fails, the app falls back to English. The finally block renders in both cases, so a failed request never leaves the user with a blank page.
The cost is that nothing appears until the catalog arrives. For small JSON files this is usually a few tens of milliseconds. For slow networks, consider rendering a lightweight static shell in index.html while the script loads.
Showing progress during a runtime switch
At runtime, the switcher calls loadLocale, which takes time. Track the pending state so the control gives feedback and ignores repeated clicks:
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { loadLocale } from './loadLocale';
const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
];
export function LanguageSwitcher() {
const { i18n } = useTranslation();
const [pending, setPending] = useState(false);
const [failed, setFailed] = useState(false);
async function change(code: string) {
setPending(true);
setFailed(false);
try {
await loadLocale(code);
document.documentElement.lang = code;
document.documentElement.dir = i18n.dir(code);
} catch {
setFailed(true);
} finally {
setPending(false);
}
}
return (
<>
<select
value={i18n.resolvedLanguage}
disabled={pending}
aria-busy={pending}
onChange={(e) => change(e.target.value)}
>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code}>{l.label}</option>
))}
</select>
{failed && <p role="alert">Could not load that language.</p>}
</>
);
}The select keeps showing the old language until changeLanguage completes, because i18n.resolvedLanguage only updates then. If the import fails, the language does not change and the user sees an error. The error message here is in English because the target catalog is unavailable. Put it in the fallback catalog in a real app and use t.
Namespaces: splitting a catalog further
One file per locale is the simplest layout. Large apps often split further by feature, so the checkout page's messages load only when the user reaches checkout. i18next calls these groups namespaces.
export async function loadNamespace(code: string, ns: string) {
if (!i18n.hasResourceBundle(code, ns)) {
const messages = await import(`./locales/${code}/${ns}.json`);
i18n.addResourceBundle(code, ns, messages.default);
}
}A component then names its namespace with useTranslation('checkout'). If that namespace is not loaded yet, the hook suspends or renders keys, depending on the useSuspense option. Two common approaches:
- Load the namespace in the route loader before the page renders.
- Wrap the component in
<Suspense>and letuseTranslationsuspend until the namespace is registered.
Namespaces multiply the number of requests, so split only where the size gain is real. A 2 KB namespace costs more in request overhead than it saves in bytes.
Failure modes and edge cases
| Problem | Cause | Fix |
|---|---|---|
| Raw keys flash on screen | `changeLanguage` ran before `addResourceBundle` | Register the bundle first, then switch |
| Blank page at startup | The initial catalog request failed and nothing rendered | Catch the error and fall back to the default locale |
| Wrong text after fast switching | Two switches overlap and the slower request finishes last | Ignore stale results (see below) |
| Every locale downloads at once | The import path is too broad or the catalogs are imported statically elsewhere | Narrow the template path and remove static imports |
| Old text after a deploy | A cached catalog file has the same name as the new one | Use content-hashed file names, which bundlers do by default |
Race conditions between switches
Suppose a user selects German, then quickly selects French. If the French file arrives first and the German file arrives second, a naive implementation ends in German while the user last chose French. Guard against this by remembering the latest request:
import i18n from './i18n';
let latest = 0;
export async function loadLocale(code: string) {
const ticket = ++latest;
if (!i18n.hasResourceBundle(code, 'translation')) {
const messages = await import(`./locales/${code}.json`);
i18n.addResourceBundle(code, 'translation', messages.default);
}
if (ticket === latest) {
await i18n.changeLanguage(code);
}
}Both bundles are still registered, which is harmless and saves a request later. Only the most recent request changes the active language. The disabled select in the earlier switcher prevents most overlaps, but programmatic calls such as a URL change can still overlap.
Prefetching
If you can predict the next locale, load it early without switching. Calling import() on hover or idle time warms the browser cache. A simple approach is to prefetch the locale from navigator.languages when it differs from the active one, so a later switch is instant.
What to check before shipping
- Open the network panel with a fresh cache and confirm the first load requests only the fallback catalog and the chosen one.
- Throttle the network to "Slow 3G" and confirm the switcher shows its pending state.
- Block one catalog file and confirm the user sees the error message and the old language stays active.
- Build the app and list the output files. You should see one JSON-derived chunk per locale.
Exercise
A user selects Spanish, then immediately selects Italian. The Italian catalog arrives first and the Spanish catalog arrives second. With the first version of loadLocale in this chapter, which language is active at the end, and how does the ticket counter change that?
Show answer
With the first version, the app ends in Spanish. Each call awaits its own import, and the Spanish call finishes last, so its changeLanguage('es') runs last and overrides the user's final choice. With the ticket counter, the Spanish call holds ticket 1 but latest is already 2 when it finishes. It still registers the Spanish bundle but skips changeLanguage, so Italian stays active.
Exercise
Why does the startup code render the app inside finally rather than only after a successful loadLocale(saved)?
Show answer
If the saved locale fails to load, rendering only on success would leave the page blank. The catch falls back to English, and finally renders the app whether the load succeeded or the fallback was used, so the user always gets a working UI.