Sub topic 9
Detecting and switching the locale at runtime
This chapter assumes you have react-i18next set up with at least two catalogs, as in the earlier chapters. You should be comfortable with React hooks and async/await. By the end you will detect a starting language, change it at runtime, and remember the choice.
Choosing the starting locale
The app needs a locale before it renders. Common sources, from strongest to weakest signal:
- A saved user choice, for example in
localStorage. - The locale in the URL (covered in a later chapter).
- The browser's
navigator.languages, an ordered list of the user's preferred language tags. - A default, which is your
fallbackLng.
The helper below matches the browser list against the languages you support. It tries the full tag first (de-AT), then the base language (de).
const SUPPORTED = ['en', 'de'];
export function detectLocale(saved: string | null): string {
if (saved && SUPPORTED.includes(saved)) return saved;
for (const tag of navigator.languages) {
if (SUPPORTED.includes(tag)) return tag;
const base = tag.split('-')[0];
if (SUPPORTED.includes(base)) return base;
}
return 'en';
}Always validate a saved value against SUPPORTED. Stored data can be stale or edited, and an unknown code would leave users on missing translations.
Pass the result to lng when you initialise i18next:
i18n.use(initReactI18next).init({
resources,
lng: detectLocale(localStorage.getItem('locale')),
fallbackLng: 'en',
interpolation: { escapeValue: false },
});Switching at runtime
i18n.changeLanguage(code) returns a promise. It updates the active language and notifies every component that uses useTranslation, so they re-render with the new text. You do not need to reload the page.
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 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.
The lang and dir lines are explained in the next chapter. They are included here so the switcher is complete.
Common errors
- Using
i18n.languageas the selected value. It can hold a regional tag such asen-USthat matches no option. Usei18n.resolvedLanguage, which is the language actually used for lookups. - Not awaiting
changeLanguage. Settinglangbefore the promise resolves can leave the page state out of step. This matters most once catalogs load on demand. - Skipping validation. Trusting
navigator.languagesor storage without checking it against your supported list. - Detecting on every render. Detect once at startup. Afterwards the user's explicit choice should win.
Exercise
A user's browser lists ['fr-CA', 'de-AT'] and your app supports only en and de. They have no saved choice. What does detectLocale(null) return, and why?
Show answer
It returns 'de'. fr-CA has no match and its base fr is unsupported, so the loop moves on. de-AT is not supported either, but its base de is, so de is returned. Falling through to 'en' happens only if no tag matches at all.