🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

React i18n: Plurals, Numbers and Locale Switching

React Utilities🟢 Free Lesson

Shipping a second language is rarely blocked by the translation library and almost always blocked by the strings you wrote before anyone thought about a second language. Hard-coded sentence fragments stitched together in JSX cannot be reordered for a language where the adjective comes first, plural rules cannot be applied to a count embedded mid-sentence, and dates arrive formatted for your locale regardless of where the reader sits. Internationalization done properly means moving every user-visible decision about language, number, date and direction out of the component and into data.

ℹ️Interpolation is not translation

Replacing a name inside an English sentence is interpolation. Translation is allowing the whole sentence to be restructured: a message may need the count first, the verb last, or two completely different strings selected by a grammatical category that English does not have. Design for the second case from the start.

Messages translators can actually work with

A catalogue keyed by stable identifiers, with one complete sentence per key, is the difference between a translator who can work and one who files questions for a week. Keys describe intent rather than English wording, so the source language can change without renaming everything, and every message is stored whole so the translator owns word order.

import i18n from 'i18next';
import { initReactI18next, useTranslation } from 'react-i18next';

const resources = {
  en: {
    translation: {
      cart: {
        title: 'Your cart',
        count: '{{count}} item in your cart',
        total: 'Total: {{amount}}',
        checkout: 'Proceed to checkout',
        empty: 'Your cart is empty. Browse the catalogue to add something.',
      },
      account: {
        greeting: 'Hello, {{name}}!',
        lastSeen: 'You last signed in on {{date}}',
      },
    },
  },
  es: {
    translation: {
      cart: {
        title: 'Tu carrito',
        count: '{{count}} artículo en tu carrito',
        total: 'Total: {{amount}}',
        checkout: 'Finalizar la compra',
        empty: 'Tu carrito está vacío. Explora el catálogo para añadir algo.',
      },
      account: {
        greeting: 'Hola, {{name}}!',
        lastSeen: 'La última vez que iniciaste sesión fue el {{date}}',
      },
    },
  },
};

i18n.use(initReactI18next).init({
  resources,
  lng: 'en',
  fallbackLng: 'en',
  interpolation: { escapeValue: false },
  returnObjects: true,
});

function CartSummary({ items, amount }) {
  const { t, i18n } = useTranslation();

  if (items.length === 0) {
    return <p>{t('cart.empty')}</p>;
  }

  return (
    <section>
      <h2>{t('cart.title')}</h2>
      <p>{t('cart.count', { count: items.length })}</p>
      <p>{t('cart.total', { amount })}</p>
      <button>{t('cart.checkout')}</button>
      <select
        aria-label="Language"
        value={i18n.language}
        onChange={(e) => i18n.changeLanguage(e.target.value)}
      >
        <option value="en">English</option>
        <option value="es">Espaol</option>
      </select>
    </section>
  );
}

Two conventions make this maintainable. Namespaces group related messages so a feature team can own one section of the file without merge conflicts on every line, and interpolation values are passed as named fields rather than positional ones, so a translator can use the count twice or not at all.

Plurals, ordinals and grammatical categories

English has two plural forms and most languages have more. Russian has three, Arabic has six, and Polish distinguishes counts ending in specific digits. The rule is not cosmetic: choosing the wrong form marks your product as untranslated even when every word is correct. Unicode defines the categories, and the browser exposes them through Intl.PluralRules, which returns the category such as one, few, many or other for a given number in a given locale.

// Intl is a browser and Node global, so there is nothing to import here
const messages = {
  en: {
    inbox: { one: 'You have {{count}} unread message', other: 'You have {{count}} unread messages' },
    results: { one: '{{count}} result for', other: '{{count}} results for' },
  },
  pl: {
    inbox: { one: '{{count}} nieprzeczytana wiadomość', few: '{{count}} nieprzeczytane wiadomości',
             many: '{{count}} nieprzeczytanych wiadomości', other: '{{count}} wiadomości' },
    results: { one: '{{count}} wynik dla', few: '{{count}} wyniki dla',
               many: '{{count}} wyników dla', other: '{{count}} wyników dla' },
  },
};

export function localizedMessage(locale, key, count) {
  const rules = new Intl.PluralRules(locale);
  const category = rules.select(count);
  const forms = messages[locale][key];
  const template = forms[category] || forms.other;
  return template.replace('{{count}}', new Intl.NumberFormat(locale).format(count));
}

Notice that the count is formatted for the locale as well as used for category selection. In locales that group with a different digit or use a different numeral system, formatting and plural selection must agree, and passing the raw number into a string that later gets displayed creates exactly the mismatch users notice first.

Dates, numbers and currency without a library

The platform already ships the formatting layer, and it is more complete than most libraries. Intl handles dates, relative times, numbers, currency, units and list conjunctions, and every one of these respects the reader's locale automatically when you pass it through.

TaskAPIExample output in en-USExample output in de-DE
CurrencyIntl.NumberFormat(locale, style currency)1,234.56 USD1.234,56 EUR
PercentagesIntl.NumberFormat(locale, style percent)42.5%42,5 %
DatesIntl.DateTimeFormat(locale, dateStyle)Jan 5, 202605.01.2026
Relative timeIntl.RelativeTimeFormat3 days agovor 3 Tagen
File sizesIntl.NumberFormat(locale, unit)1.5 MB1,5 MB
ListsIntl.ListFormata, b and ca, b und c

Formatting has a second benefit beyond correctness: it removes an entire category of bug. A date written by hand renders as 03/04/2026 to one reader and April 3 to another, and a currency symbol placed by string concatenation is wrong for every locale that puts it after the amount.

Detecting the locale and switching at runtime

Detection should be a short ladder rather than a single guess. Read an explicitly stored preference first, because a user who chose a language should never be re-detected. Fall back to the account locale, then to the browser languages list, and finally to the default. Never derive the language from a URL segment alone unless routing is part of your product contract, and never silently switch after the first render, because the flash of the wrong language reads as a bug.

Switching at runtime should be one function call that updates the catalogue, persists the choice, and lets React re-render. Everything derived from the locale, including formatted dates and plural lookups, must be computed during render rather than cached in module scope, or the visible numbers will keep the previous language after the strings change.

Loading only the locales you need

Bundling every translation into the initial JavaScript is a common way to give a ten megabyte payload to a reader who needs one language. The catalogue for a mature product routinely reaches tens of kilobytes per locale, and shipping all of them means every visitor downloads languages they will never read. Load the default locale eagerly, then fetch the rest on demand and hand them to the catalogue before switching.

import i18n from 'i18next';

const loaded = new Set(['en']);

export async function ensureLocale(locale) {
  if (loaded.has(locale)) return locale;

  const module = await import(`./locales/${locale}.js`);
  i18n.addResourceBundle(locale, 'translation', module.default, true, true);
  loaded.add(locale);
  return locale;
}

export async function switchLocale(locale, store) {
  await ensureLocale(locale);
  await i18n.changeLanguage(locale);
  store.setPreference('locale', locale);
  document.documentElement.lang = locale;
}

Three details in that snippet do real work. The bundle is added with deep merge enabled so a partially translated locale falls back to the default for missing keys rather than rendering blanks. The chosen locale is persisted, so the next visit starts in the right language without waiting for detection. And the lang attribute on the document element is updated, which screen readers use to pick a pronunciation voice and search engines use to index the page correctly.

Preloading the neighbouring locale on a hover or a route change hides the network round trip entirely. For larger catalogues, split by namespace rather than by locale so a reader who only opens the settings screen never downloads the checkout messages.

Layout that survives translation

Right-to-left languages double the work if you assumed left-to-right. Physical properties such as margin-left and right float push content the wrong way, so logical properties, margin-inline-start and padding-inline-end, let the browser mirror them automatically. Text alignment, the direction of a chevron icon, and the order of a two-column grid all follow from setting the direction attribute on the root element.

Length is the other silent failure. German compounds and French formal phrasing routinely expand a label by forty percent, which overflows a fixed-width button. Test with a pseudo-locale that appends padding to every string: if the layout survives that, real translations usually will too. The same test catches truncation in tables and navigation, where a longer word pushes an icon onto a second line long before anyone files a bug.

Common Mistakes

Concatenating fragments of sentences in JSX so they can be reordered later

Fix: Store each complete sentence as one message and let the translator own the order through interpolation.

Using an English-only singular and plural pair for every locale

Fix: Select the form with Intl.PluralRules for the active locale, and provide every category your languages require.

Formatting dates and currency with manual string operations

Fix: Use the Intl constructors with the reader's locale so separators, ordering and symbols come out correct by construction.

Persisting nothing about the language choice

Fix: Save the preference, detect it first on every visit, and only fall back to browser detection when no choice exists.

Best Practices

  • Keep message keys feature-scoped and review new strings for interpolation points before they reach translation
  • Format every number, date and unit through Intl during render so a language switch updates all of them at once
  • Test layout with an expanding pseudo-locale to catch fixed-width components before a translator does
  • Set direction on the document root and prefer logical CSS properties over physical left and right rules

Key Takeaways

  • One message per key, stored whole, is what lets translators restructure sentences without breaking the app
  • Plural categories come from Intl.PluralRules and differ per language, so a two-form English approach is wrong elsewhere
  • Intl covers currency, dates, relative time and lists with locale-correct output and no extra dependency
  • Detect language in a ladder: stored preference, account locale, browser list, then default, and never re-detect a saved choice
  • Use logical CSS properties and set direction so right-to-left languages mirror the layout instead of breaking it
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement