A guest from Japan is watching a film on the TV in the Mist Homestay lounge and switches the subtitles to Japanese. The film doesn't restart, the scene stays at the same minute. The Japanese subtitles may take a second to download, and tomorrow the TV still remembers the choice. Mrs. Sri's page should do the same. Dynamic language switching means the page that's already open changes language without a reload, without losing the guest's choices, and remembers the choice for the next visit. The TV's four things are this lesson: no reload, state kept, dictionaries loaded when picked, the choice saved.
Switch without a reload: changeLanguage
The old way to switch languages was to reload the page, for example location.href = '?lng=ja-JP'. All the JavaScript downloads again, and the 3-night choice goes back to 2 nights, its starting value. With i18next (the "i18next Setup" lesson), one call is enough:
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
function BookingCard() {
const { t, i18n } = useTranslation('booking');
const [nights, setNights] = useState(2);
return (
<section>
<h1>{t('room')}</h1>
<button onClick={() => setNights(3)}>{t('nights', { count: 3 })}</button>
<p>{t('nights', { count: nights })}</p>
<button onClick={() => i18n.changeLanguage('ja-JP')}>日本語</button>
</section>
);
}
i18n.changeLanguage('ja-JP')returns a Promise. It loads the dictionary if it isn't there yet, changesi18n.language, then fires thelanguageChangedevent.- Every component that uses
useTranslationrenders again in the new language. React state isn't touched, sonightsstays 3: "Terrace Room" becomes "テラスルーム", "3 nights" becomes "3泊".
Lazy loading: the ja and ar dictionaries load when picked
A guest uses one language, so don't put all four dictionaries in the main bundle. The source language's dictionary goes in the bundle; the others load with import() when picked. Vite splits every JSON file reached through import() into a file of its own.
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import resourcesToBackend from 'i18next-resources-to-backend';
import enUS from './locales/en-US/booking.json';
i18next
.use(resourcesToBackend((lng, ns) => import(`./locales/${lng}/${ns}.json`)))
.use(initReactI18next)
.init({
lng: 'en-US',
fallbackLng: ['en-US'],
ns: ['booking'],
defaultNS: 'booking',
partialBundledLanguages: true, // en-US is in the bundle, other languages load
resources: { 'en-US': { booking: enUS } },
interpolation: { escapeValue: false },
});
We ran this setup with i18next 26.4.3, react-i18next 17.0.16 and i18next-resources-to-backend 1.2.3, with the dictionary slowed down to 300 ms on purpose. A guest has picked 3 nights on the card, still in English, then clicks "日本語". Guess first: during those 300 ms, do you see an empty card with a spinner, the old English card, or raw keys like room? Here is what happened:
| Time | What happens |
|---|---|
| 0 ms | changeLanguage('ja-JP') is called. The languageChanging event. i18n.language is still "en-US", the ja-JP dictionary starts loading. |
| 0 to 300 ms | The card stays in English: "3 nights". |
| 300 ms | The dictionary arrives. The languageChanged event, i18n.language becomes "ja-JP", the card becomes "3泊". |
| Clicking a language already loaded | It switches at once, loading nothing. |
So what shows while loading is the old English card. By default react-i18next only listens to languageChanged (the react.bindI18n option). If you add languageChanging, the component waits through Suspense and its fallback shows while loading. The old text is usually nicer to look at; just mark the clicked language button with aria-busy="true" and a small spinner, so the guest knows the click landed.
If the dictionary fails to load (a 404, say), changeLanguage('ar-EG') still finishes without an error. What we measured: i18n.language becomes "ar-EG", but i18n.resolvedLanguage becomes "en-US", and the card shows in English from fallbackLng. resolvedLanguage is the language t() actually uses.
What changes along with it: lang, dir and Intl
Changing the words isn't enough. <html lang> and dir must follow, and take them from resolvedLanguage: taken from language, an Arabic dictionary that failed to load gives English text on an rtl page.
i18next.on('languageChanged', () => {
const used = i18next.resolvedLanguage; // 'ja-JP'
document.documentElement.lang = used;
document.documentElement.dir = i18next.dir(used); // 'rtl' for ar-EG
});
Intl formatters are tied to one locale from the moment they're made, too. A formatter made once outside the component with 'en-US' keeps writing "$105" on the Arabic card. Make it again whenever the language changes:
const { i18n } = useTranslation();
const money = useMemo(
() => new Intl.NumberFormat(i18n.resolvedLanguage, { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }),
[i18n.resolvedLanguage],
);
money.format(105); // en-US "$105", id-ID "US$105", ar-EG "١٠٥ US$"
Save the choice: localStorage, cookie, URL or database
| Saved in | Does the server know on the first request? | Does it travel with a shared link? | Does it follow to another device? |
|---|---|---|---|
localStorage |
no, only JavaScript in the browser can read it | no | no |
cookie lang=ja-JP |
yes, the cookie goes with every request | no | no |
URL /ja/テラスルーム |
yes | yes | yes, through the link |
database, a locale column |
yes, if the guest is logged in | no | yes |
- localStorage: if the page is rendered on the server, the server doesn't know the choice. The first HTML is in English, then JavaScript reads
localStorageand switches to Japanese. The guest sees a flash of English. - Cookie:
document.cookie = 'lang=ja-JP; path=/; max-age=31536000; samesite=lax'. The server reads it and sends Japanese HTML straight away. - The URL wins for public pages: each language has its own address, the link a guest sends a friend carries the language, and Google can index each version (the "SEO for Multi-language" lesson). Switching language means moving to the same page under another prefix; an SPA router does that without a reload.
- The database for logged-in guests: save
localein the user table through a request to the API, so it follows them to their phone and is used for emails (the next lesson).
The combination: a cookie or localStorage for guests who aren't logged in, the database for those who are, and the URL for pages that get shared and searched. The order to read them in when a page opens: the URL prefix, then the user's locale, then the cookie, then the Accept-Language header, then en-US.
A language picker done right
<nav aria-label="Language / Bahasa">
<a href="/en/terrace-room" lang="en" hreflang="en" aria-current="page">English</a>
<a href="/id/kamar-teras" lang="id" hreflang="id">Bahasa Indonesia</a>
<a href="/ja/テラスルーム" lang="ja" hreflang="ja">日本語</a>
<a href="/ar/غرفة-التراس" lang="ar" hreflang="ar">العربية</a>
</nav>
- Write each language in itself. A Japanese guest who lands on the Arabic page can't read "اليابانية" (Japanese, in Arabic), but will always recognise "日本語".
new Intl.DisplayNames(['ja'], { type: 'language' }).of('ja')gives "日本語" and forargives "العربية", the same in Chromium 147, Firefox 146, WebKit 26.4 and Node 22.22.1. Foridit gives "Indonesia", so many sites write "Bahasa Indonesia" by hand. - Don't use flags. A flag marks a country, not a language: Arabic is official in more than 20 countries, and English doesn't belong to America alone.
langon each link makes a screen reader say "日本語" with Japanese pronunciation.aria-current="page"marks the language in use.- Plain links beat a
<select>on public pages: they open in a new tab and Google can follow them.
⚠️ What makes switching languages feel broken
- Reloading to switch language. The guest's choices (3 nights, dates, form input) are lost. Use
changeLanguage. - An
Intlformatter made once. The words are Arabic, the price still says "$105". Make it again per locale. dirfromi18n.language. If the Arabic dictionary fails to load, English text shows right to left. UseresolvedLanguage.- Only
localStorageon a server-rendered site. The first HTML is always the source language, then it flashes. Use a cookie or the URL. - Flags, and language names in the active language. Write "日本語" and "العربية", with no flags.
TL;DR: i18n.changeLanguage('ja-JP') switches language without a reload, and React state (3 nights) stays. The ja-JP and ar-EG dictionaries load with import() when picked; while loading, default react-i18next keeps showing the old language (languageChanging, then languageChanged), and a dictionary that fails to load makes resolvedLanguage fall back to fallbackLng. After switching, set <html lang> and dir from resolvedLanguage, and make the Intl formatters again. Save the choice in a cookie or localStorage for guests, in the database for logged-in users, and in the URL for pages that get shared and searched on Google (the URL wins there). The picker writes each language in itself ("日本語", "العربية"), with lang on each choice and no flags.
⚡ Switch without a reload
Write:
<button onClick={() => i18n.changeLanguage('ja-JP')}>日本語</button>
Meaning: changeLanguage loads the dictionary if it isn't there yet, changes i18n.language, then fires languageChanged. Every component that uses useTranslation renders again, and React state isn't touched: the 3-night choice stays 3.
⚡ While the dictionary loads
Guess first: during the 300 ms the ja-JP dictionary takes to load, does the guest see an empty card with a spinner, the old English card, or raw keys like room?
The old English card. By default react-i18next only listens to languageChanged, and that event fires when the dictionary arrives.
Meaning: Mark the clicked language button with aria-busy="true". If the dictionary fails to load, resolvedLanguage falls back to fallbackLng, so take lang and dir from resolvedLanguage.
⚡ Save the choice
Meaning: A cookie or localStorage for guests who aren't logged in, the database for those who are, and the URL for pages that get shared and searched. On a server-rendered site a cookie or the URL beats localStorage, because the server knows the language from the first request.