Dynamic Language Switching — i18n

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…

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>
  );
}

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

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>

⚠️ What makes switching languages feel broken

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.

What you will learn