Sub topic 9
Detecting and switching the locale at runtime
This chapter covers how an app decides which language to show first, how it changes language while running, and how it remembers the choice. It assumes you know React function components and hooks, async/await, and the react-i18next setup from the earlier chapters. That setup has an i18n instance with en and de catalogs and en as the fallback.
Why the locale is runtime state
The locale is not a build-time setting. A user can open your app with a browser set to German, then choose French from a menu, then come back next week and expect French again. The app has to do four things:
- Detect an initial locale.
- Switch locale while running.
- Persist the choice.
- Re-render everything that depends on it.
react-i18next handles the last step. Components that call useTranslation() subscribe to language changes, so they re-render when i18n.changeLanguage() finishes. The first three steps are yours to design.
Detecting the initial locale
The browser exposes the user's preferred languages as navigator.languages, an array ordered by preference, for example ['de-AT', 'de', 'en-US', 'en']. The older navigator.language holds only the first entry.
A tag such as de-AT will not match a catalog keyed de unless you resolve it. The next function walks the preference list, tries the exact tag, then the base language, and returns the first supported match.
const SUPPORTED = ['en', 'de'] as const;
export type SupportedLocale = (typeof SUPPORTED)[number];
export function pickLocale(
requested: readonly string[],
fallback: SupportedLocale = 'en',
): SupportedLocale {
for (const tag of requested) {
const lower = tag.toLowerCase();
const exact = SUPPORTED.find((s) => s === lower);
if (exact) return exact;
const base = lower.split('-')[0];
const byBase = SUPPORTED.find((s) => s === base);
if (byBase) return byBase;
}
return fallback;
}
// pickLocale(['de-AT', 'en-US']) -> 'de'
// pickLocale(['fr-FR']) -> 'en'Order matters. A user with ['fr', 'de'] gets German, because French is unsupported and German is the next preference. Checking only navigator.language would give them English.
Using a detector plugin
You can use the i18next-browser-languagedetector package instead of writing this yourself. It checks several sources in an order you configure, and it can cache the result.
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import de from './locales/de.json';
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: { en: { translation: en }, de: { translation: de } },
fallbackLng: 'en',
supportedLngs: ['en', 'de'],
nonExplicitSupportedLngs: true,
interpolation: { escapeValue: false },
detection: {
order: ['querystring', 'localStorage', 'navigator'],
lookupQuerystring: 'lng',
lookupLocalStorage: 'locale',
caches: ['localStorage'],
},
});
export default i18n;Points to check in this configuration:
- Do not set
lngwhen you use the detector. A fixedlngoverrides detection. supportedLngslimits detection to languages you ship.nonExplicitSupportedLngs: trueletsde-ATmatchde.orderis a priority list. An explicit URL parameter wins over a stored choice, and a stored choice wins over the browser setting.cachestells the detector where to write the language after a change. ThelookupLocalStoragekey and the cache key are the same entry.
Switching the locale
i18n.changeLanguage(code) returns a promise. It resolves after the new language is active and any needed resources are loaded. Await it before you do work that depends on the new language.
The switcher below is a controlled <select>. It follows the earlier example and also stores the choice, so it works even if you do not use the detector's cache.
import { useTranslation } from 'react-i18next';
const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
];
export function LanguageSwitcher() {
const { i18n } = useTranslation();
async function change(code: string) {
await i18n.changeLanguage(code);
localStorage.setItem('locale', code);
document.documentElement.lang = code;
document.documentElement.dir = i18n.dir(code);
}
return (
<select
aria-label="Language"
value={i18n.resolvedLanguage}
onChange={(e) => change(e.target.value)}
>
{LANGUAGES.map((l) => (
<option key={l.code} value={l.code}>{l.label}</option>
))}
</select>
);
}Each language is labelled in its own language (Deutsch, not German). A user who cannot read the current interface can still find their language.
`language` versus `resolvedLanguage`
These two properties differ, and mixing them up causes a common bug.
| Property | Meaning | Example after detection on `de-AT` |
|---|---|---|
| `i18n.language` | The detected or requested tag, as given | `de-AT` |
| `i18n.resolvedLanguage` | The language whose catalog is actually used | `de` |
Use resolvedLanguage for the value of a <select>. With language, the value de-AT matches no option, and the control shows the wrong entry. Use i18n.language when you pass a tag to Intl, because de-AT carries regional formatting that de does not.
Keeping Intl formatting in step
The Intl objects from the formatting chapter take a locale argument. If you hard-code 'en-US' there, the text will switch language while the numbers and dates stay the same. Read the active locale from the hook instead.
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
export function Price({ amount }: { amount: number }) {
const { i18n } = useTranslation();
const formatter = useMemo(
() => new Intl.NumberFormat(i18n.language, { style: 'currency', currency: 'EUR' }),
[i18n.language],
);
return <span>{formatter.format(amount)}</span>;
}The formatter is built once per language, not once per render. Creating Intl objects is relatively expensive, so memoising them is worthwhile in lists.
Persisting and sharing the choice
You have several places to store the locale. Each one suits a different case.
| Storage | Survives reload | Visible to server | Best for |
|---|---|---|---|
| `localStorage` | Yes | No | Single-page apps without server rendering |
| Cookie | Yes | Yes | Apps that render on the server and need the locale on the first request |
| URL path or query | Yes, and shareable | Yes | Public pages, search engines, shared links |
| Account profile | Across devices | Yes | Signed-in users |
A later chapter on server rendering covers cookies and URL paths. For a client-only app, localStorage is enough.
Common errors
- Wrong language flashes on load. React renders once with the fallback, then the detected language arrives. With bundled catalogs and the detector, detection is synchronous, so this does not happen. With lazy-loaded catalogs it can. Show a loading state until
changeLanguageresolves. - Switcher shows the wrong option. The
valueusesi18n.language(de-AT) instead ofresolvedLanguage. - Dates stay in English. The code passes a literal locale to
Intl, or builds a formatter at module level that never updates. - Detection never runs. The
initcall setslng, which takes priority over the detector. - Reading direction does not change. The code updates
i18nbut notdocument.documentElement.dir. The next chapter makes this automatic. - A saved value breaks the app. A user has
locale=jain storage from an older version, and you no longer ship it. PassingsupportedLngsmakes i18next ignore it. In your own code, run stored values throughpickLocale.
Reacting to changes outside React
Sometimes non-component code needs to know about a language change, for example to update document.title or to tell an analytics tool. i18next emits a languageChanged event.
import i18n from './i18n';
function onLanguageChanged(lng: string) {
document.documentElement.lang = lng;
document.documentElement.dir = i18n.dir(lng);
}
i18n.on('languageChanged', onLanguageChanged);
onLanguageChanged(i18n.language);Registering one listener at start-up keeps lang and dir correct for every source of change, including detection at load, a switcher, and a test. The explicit first call covers the initial language, because the detector may have set it before your listener was attached.
Exercise
A user's browser lists ['fr-CA', 'de-CH', 'en'] as preferred languages. Your app ships only en and de. Using the pickLocale function from this chapter, which locale is chosen, and why? Then say which property you would give to a <select> as its value if i18next had detected de-CH.
Show answer
The result is de. fr-CA has no exact or base match in the supported list, so the loop moves on. de-CH has no exact match, but its base de matches, so de is returned before en is considered. For the <select>, use i18n.resolvedLanguage (de), because i18n.language would be de-CH, which matches no option.
Exercise
You add i18next-browser-languagedetector and keep lng: 'en' in init. Every visitor sees English, whatever their browser setting. What is wrong and how do you fix it?
Show answer
A fixed lng takes priority over the detector, so detection result is ignored. Remove lng from the init options and keep fallbackLng: 'en'. The detector then sets the language from the configured sources, and English is used only when none match a supported language.