Skip to content

Optional analytics, session recording and advertising stay off unless you accept. You can reject them and use Transglot. Change your choice anytime in Cookie preferences. Cookie Policy

Back to the blog
Developer platform

React Localization: The Complete i18n Guide (2026)

React i18n for a Vite app: react-i18next and react-intl setup, plurals, Trans, lazy loading, React Router, right to left, tests, CI and AI translation checks.

by transglot team
published November 24, 2026
26 min read

Documentation reviewed 23 November 2026.

Quick answer

React has no built-in i18n, so you pick a library. For most single-page apps that is react-i18next: install i18next and react-i18next, call i18n.use(initReactI18next).init(...) once, and read strings with const { t } = useTranslation(). Translations live in one JSON file per language and namespace, placeholders are written {{name}}, and plurals are separate keys with suffixes such as _one and _other. If your translators or tools expect ICU MessageFormat, use react-intl, where a plural is one message: {count, plural, one {# item} other {# items}}. Either way, dates, numbers and lists go through the browser's Intl API, and the locale belongs in the URL.

What you will have at the end

This guide is for developers who own a client-rendered React app built with Vite. For Next.js, read how to translate a React or Next.js app automatically. The samples target React 19.3, Vite 8, i18next 27.2, react-i18next 18.0, i18next-browser-languagedetector 8.3, i18next-resources-to-backend 1.3, i18next-cli 1.94, react-intl 12.2, @formatjs/cli 6.23, React Router 8.5, Vitest 5.1 and React Testing Library 16.3, the current releases on npm at the review date. By the end you will have:

  • A library chosen for a reason you can defend.
  • Every string read from locale files, with plurals that are correct in languages with four or six forms.
  • Markup inside sentences, formatted dates and numbers, typed keys.
  • Locale files loaded on demand, the locale in the URL, and the choice remembered.
  • A layout that works right to left and reads correctly in a screen reader.
  • Tests and a CI job that fail on a missing or malformed translation.
  • A way to translate the files with AI and check what comes back.
A cream paper-pulp browser window on a stone plinth with four paper drawers below it, each drawer a different depth, one pulled open
Four libraries, two message styles, one set of locale files

Part 1: choose a library

LibraryMessage styleWhere messages liveFits
react-i18next 18 (on i18next 27)i18next JSON: {{name}}, suffix keys for plurals, $t() nestingA JSON file per language and namespaceApps that want keys in code, namespaces loaded on demand, and plugins for detection and loading
react-intl 12 (FormatJS)ICU MessageFormat: {name}, plural, select, tagsDefault messages in code, extracted to JSON by a CLITeams whose translators or vendor tools already work in ICU, and apps that want formatting components
Lingui 6ICU, generated from JSX by macrosPO catalogs by default, compiled before useTeams that prefer writing the source text in the component and never naming a key
Paraglide JS 3Messages compiled to functionsmessages/en.json, compiled into a folder of modulesApps where unused messages should be removed by the bundler

Each row is from the library's own documentation. Lingui needs Node.js 22.19 or later. Paraglide's site adds that tree-shaking removes unused message functions but not inactive locales.

i18next can also read ICU through the i18next-icu plugin, so the message style is not locked to the library. The rest of this guide builds on react-i18next and shows the same tasks in react-intl in Part 6. Conventions for key names and file layout are in i18next best practices.


Part 2: set up react-i18next

bashbash
npm install i18next react-i18next

react-i18next 18 needs i18next 27 and React 18 or later.

Write the first locale file

src/locales/en/translation.jsonjson
{
"app": { "name": "Northwind" },
"language": { "label": "Language" },
"home": {
"title": "Welcome to $t(app.name)",
"greeting": "Hello, {{name}}"
},
"inbox": {
"unread_one": "{{count}} unread message",
"unread_other": "{{count}} unread messages",
"summary_one": "Hello <bold>{{name}}</bold>, you have {{count}} unread message. <inbox>Open the inbox</inbox>.",
"summary_other": "Hello <bold>{{name}}</bold>, you have {{count}} unread messages. <inbox>Open the inbox</inbox>."
},
"invite": "Invite them",
"invite_male": "Invite him",
"invite_female": "Invite her",
"order": {
"total": "Total: {{val, currency(EUR)}}",
"due": "Due on {{val, datetime}}"
}
}

translation is the default namespace. Nested objects become dotted keys: home.title.

Initialise once

src/i18n.jsjs
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en/translation.json';
import ru from './locales/ru/translation.json';
i18n.use(initReactI18next).init({
lng: 'en',
fallbackLng: 'en',
resources: { en: { translation: en }, ru: { translation: ru } },
interpolation: { escapeValue: false },
});
export default i18n;

Import the file once in src/main.jsx, before the app renders: import './i18n';. initReactI18next passes the instance to every component, so no provider is needed.

Use it in a component

jsxjsx
import { useTranslation } from 'react-i18next';
export function Header({ name, count }) {
const { t } = useTranslation();
return (
<header>
<h1>{t('home.title')}</h1>
<p>{t('home.greeting', { name })}</p>
<p>{t('inbox.unread', { count })}</p>
</header>
);
}

The hook returns t and the i18n instance, and renders the component again when the language changes. Outside a component, import the instance and call i18n.t('home.title').

There is no fallback language by default. Without fallbackLng, a key missing from the active language prints the key itself, such as inbox.nope. Set it to the language your source text is written in.
Watch out

Part 3: the i18next message format

FeatureIn the fileCallResult
InterpolationHello, {{name}}t('home.greeting', { name: 'Ada' })Hello, Ada
Pluralunread_one, unread_othert('inbox.unread', { count: 5 })5 unread messages
Contextinvite_male, invite_femalet('invite', { context: 'female' })Invite her
NestingWelcome to $t(app.name)t('home.title')Welcome to Northwind
FormatTotal: {{val, currency(EUR)}}t('order.total', { val: 1234.5 })Total: €1,234.50

Interpolation and escaping

i18next escapes interpolated values by default: with escapeValue: true, a name of <b>Ada</b> came out as &lt;b&gt;Ada&lt;/b&gt; in the test for this guide. React already escapes the text it renders, which is why the React setup turns it off. Keep it on if you ever pass t() output to dangerouslySetInnerHTML. Inside a message, {{- name}} switches escaping off for one value.

Plurals

Pass the number as count. i18next asks Intl.PluralRules for the category and looks up the key with that suffix. Without count, t('inbox.unread') looks up inbox.unread only and prints the key.

English has two categories. Other languages have more, and each one needs its own key:

LanguageSuffix keys needed
Japanese_other
English, German_one, _other
French, Spanish_one, _many, _other
Russian, Polish, Ukrainian_one, _few, _many, _other
Arabic_zero, _one, _two, _few, _many, _other
src/locales/ru/translation.jsonjson
{
"inbox": {
"unread_one": "{{count}} непрочитанное сообщение",
"unread_few": "{{count}} непрочитанных сообщения",
"unread_many": "{{count}} непрочитанных сообщений",
"unread_other": "{{count}} непрочитанного сообщения"
}
}

With that file, counts of 1, 3, 5 and 21 printed the one, few, many and one forms. To list the categories for a language, run new Intl.PluralRules('ar').resolvedOptions().pluralCategories.

From the plurals page: a _zero key, where present, wins for count: 0 in any language. Since i18next 27.1, a missing form falls back to _other of the same language. The French and Spanish many form applies to exact millions, so most files leave it out and rely on that fallback. Ordinals use ordinal: true and keys such as place_ordinal_one.

Two rows of cream paper-pulp key tags on a stone plinth: two tags in the first row, four in the second, each tag with a short suffix label
English needs two suffix keys for a plural. Russian needs four.

Context and nesting

context picks a variant by suffix, and an unknown context falls back to the plain key. With count, the plural suffix follows the context: invite_male_one. $t(key) inserts another translation, so a product name is written once. A key in another namespace is written $t(common:app.name).

Put the whole sentence in every plural form. A translated noun glued to English text in JSX forces English word order on every language. i18next-cli lint flags translated strings joined with + for this reason.
Rule

Part 4: markup inside a sentence with `Trans`

"Hello Ada, you have 3 unread messages. Open the inbox." has a bold name and a link. Split into pieces, it cannot be reordered by a translator. Trans keeps it as one string:

jsxjsx
import { Trans } from 'react-i18next';
export function Summary({ name, count }) {
return (
<p>
<Trans
i18nKey="inbox.summary"
count={count}
values={{ name }}
components={{ bold: <strong />, inbox: <a href="/inbox" /> }}
/>
</p>
);
}

With name="Ada" and count={3} this rendered Hello <strong>Ada</strong>, you have 3 unread messages. <a href="/inbox">Open the inbox</a>.

Prefer named tags. The other form writes the sentence as JSX children, and the translation refers to each child by position: Hello <1>{{name}}</1>, ... <5>Go to messages</5>. The documentation calls those indexed tags hard to guess, and a formatter that inserts {' '} at a line break shifts every later index.

Details from the documentation:

  • Names of self-closing HTML tags, such as link and img, are reserved and do not work as component names.
  • br, strong, i and p without attributes keep their own names in a translation (transKeepBasicHtmlNodesFor).
  • In version 18, Trans renders interpolated values as text whatever escapeValue is set to.

Part 5: namespaces, lazy loading, detection and fallback

Namespaces

A namespace is one file: common.json, admin.json. A component names the ones it needs with useTranslation(['common', 'admin']). t looks in the first, and t('title', { ns: 'admin' }) in another.

Load files on demand

Two documented ways to keep unused languages out of the first download:

BackendHow it loadsFits
i18next-resources-to-backendA dynamic import(), so the bundler emits one chunk per language and namespaceVite apps that ship translations with the build
i18next-http-backendfetch from loadPath, by default /locales/{{lng}}/{{ns}}.json under public/Files served or updated separately from the app
bashbash
npm install i18next-resources-to-backend i18next-browser-languagedetector
src/i18n.js, replacing the version in Part 2js
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import resourcesToBackend from 'i18next-resources-to-backend';
import { initReactI18next } from 'react-i18next';
export const SUPPORTED = ['en', 'ru', 'ar'];
export const ready = i18n
.use(resourcesToBackend((language, namespace) =>
import(`./locales/${language}/${namespace}.json`)))
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
supportedLngs: SUPPORTED,
load: 'languageOnly',
ns: ['translation'],
defaultNS: 'translation',
detection: {
order: ['path', 'localStorage', 'navigator'],
lookupFromPathIndex: 0,
lookupLocalStorage: 'i18nextLng',
caches: ['localStorage'],
},
interpolation: { escapeValue: false },
});
i18n.on('languageChanged', (lng) => {
document.documentElement.lang = lng;
document.documentElement.dir = i18n.dir(lng);
});
export default i18n;

Leave lng out when a detector is registered. init returns a promise, exported here as ready for the router in Part 10. load: 'languageOnly' turns a detected en-US into en, and supportedLngs lets i18next pick the best match from what the detector found.

Suspense

While a namespace is loading, useTranslation suspends the component. Wrap the app in <Suspense fallback={...}>, or you get a blank screen and React's "suspended while rendering, but no fallback UI was specified" error. The alternative is useTranslation('ns', { useSuspense: false }) and the ready flag it returns.

Detection and persistence

The detector reads the sources in order, and i18next takes the first detected language that is in supportedLngs. Here the first URL segment comes first, then the saved choice, then the browser language. caches: ['localStorage'] saves every change under the i18nextLng key, so calling i18n.changeLanguage('ru') is all a language switch has to do. Read i18n.resolvedLanguage for the language in use: i18n.language can hold the raw detected tag.

Fallback order

For each key, i18next tries the key's forms (context, then plural, then plain), then the languages (de-CH, then de, then fallbackLng), then fallbackNS, and last returns the key. fallbackLng also takes an array or a map per language. An empty string in a file counts as missing.


Part 6: the same tasks in react-intl

bashbash
npm install react-intl

react-intl has no keys with suffixes. A message is one ICU string with an id:

src/lang/en.jsonjson
{
"home.greeting": "Hello, {name}",
"inbox.unread": "{count, plural, one {# unread message} other {# unread messages}}",
"inbox.summary": "Hello <b>{name}</b>, you have {count, plural, one {# unread message} other {# unread messages}}. <a>Open the inbox</a>.",
"invite": "{gender, select, male {Invite him} female {Invite her} other {Invite them}}"
}
jsxjsx
import { IntlProvider } from 'react-intl';
import messages from './lang/en.json';
export function Root() {
return (
<IntlProvider locale="en" defaultLocale="en" messages={messages}>
<App />
</IntlProvider>
);
}
jsxjsx
import { FormattedMessage, useIntl } from 'react-intl';
export function Inbox({ name, count }) {
const intl = useIntl();
return (
<section>
<input aria-label={intl.formatMessage({ id: 'home.greeting' }, { name })} />
<FormattedMessage id="inbox.unread" values={{ count }} />
<FormattedMessage
id="inbox.summary"
values={{
name,
count,
b: (chunks) => <strong>{chunks}</strong>,
a: (chunks) => <a href="/inbox">{chunks}</a>,
}}
/>
</section>
);
}

useIntl().formatMessage returns a string for attributes. Rich text is a tag in the message resolved by a function in values, and defaultRichTextElements on the provider sets shared tags once.

Taskreact-i18nextreact-intl
Placeholder{{name}}{name}
PluralOne key per category: key_one, key_fewOne message: {count, plural, one {...} other {...}}
Variantcontext and a suffix key{gender, select, ... other {...}}
Ordinalordinal: true, key_ordinal_one{n, selectordinal, ...}
Markup<Trans components={...}>Tags resolved in values
Reuse a string$t(key)Not part of ICU
Missing messageFalls back, then prints the keyRenders defaultMessage or the id, and calls onError

Rules the ICU syntax page states: other is required in plural, select and selectordinal, and leaving it out is an error. # prints the number. Do not write =1 where you mean one, because one is not always the number 1. An ASCII apostrophe escapes syntax characters, so use the curly apostrophe in prose.

A Russian ICU plural has four branches in one string, where i18next has four keys. Because messages is a prop, lazy loading is a dynamic import() of the locale file before the provider renders.


Part 7: dates, numbers, currency, lists and relative time

Never build these by hand. Both libraries delegate to Intl:

Valuei18next format in a messagereact-intl componentEnglish output
Number{{val, number}}<FormattedNumber value={1000} />1,000
Currency{{val, currency(EUR)}}<FormattedNumber style="currency" currency="EUR" />€1,234.50
Date{{val, datetime}}<FormattedDate dateStyle="long" />November 23, 2026
Relative time{{val, relativetime}}<FormattedRelativeTime value={-3} unit="day" />3 days ago
List{{val, list}}<FormattedList type="conjunction" />apples, pears, and plums

In i18next, options go in the call: t('order.due', { val: date, formatParams: { val: { dateStyle: 'long' } } }). In Russian, order.total printed "1 234,50 €". In react-intl, intl.formatNumber, formatDate, formatRelativeTime and formatList return strings.

A currency format changes separators and symbol position. It does not convert the amount. Keep the currency code in your data, not in the translation, unless a translator should be able to change it.
Watch out

Part 8: typed keys with TypeScript

For i18next, one declaration file makes t() reject unknown keys:

src/@types/i18next.d.tsts
import 'i18next';
import type translation from '../locales/en/translation.json';
declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'translation';
resources: { translation: typeof translation };
}
}

With this file and resolveJsonModule on, t('home.greting') failed to compile with "Did you mean 'home.greeting'?". npx i18next-cli types generates the same declarations from your files, and types --ci fails when they are out of date. The documentation also lists strictInterpolationChecks, which requires the options for a string with {{variables}}.

In react-intl 12, the ESLint rule formatjs/enforce-message-types reads each ICU message and writes its argument types onto defineMessage. Lingui has lingui compile --typescript, and Paraglide's generated functions are typed by construction.


Part 9: extract strings from code

LibraryCommandWhat it does
i18nextnpx i18next-cli extractFinds the keys in .js, .jsx, .ts and .tsx files and writes them into every language's file, including each language's plural suffixes
react-intlformatjs extract "src/**/*.tsx" --out-file lang/en.jsonCollects defaultMessage and description from FormattedMessage, formatMessage and defineMessages
Linguilingui extract, then lingui compileWrites catalogs from the macros, then compiles them for the runtime
i18next.config.tsts
import { defineConfig } from 'i18next-cli';
export default defineConfig({
locales: ['en', 'ru', 'ar'],
extract: {
input: ['src/**/*.{js,jsx,ts,tsx}'],
output: 'src/locales/{{language}}/{{namespace}}.json',
},
lint: { checkTranslationPlaceholders: 'error' },
});

i18next-parser, which older tutorials use, has been unmaintained since September 2025. Its README points to i18next-cli, and npx i18next-cli migrate-config converts the old configuration. Static extraction cannot see a key built at run time.

With FormatJS, formatjs extract writes { id: { defaultMessage, description } }. formatjs compile turns a translated file into what IntlProvider takes, and --ast pre-parses messages so the browser does not. A flat { id: message } file compiles with --format simple.


Part 10: the locale in the URL with React Router

A locale kept only in localStorage cannot be linked to or bookmarked. Make it the first path segment and let the route loader switch language before the page renders:

src/router.jsx, React Router 8 in data modejsx
import { createBrowserRouter, Outlet, redirect } from 'react-router';
import i18n, { ready, SUPPORTED } from './i18n';
import { Home } from './pages/Home';
export const router = createBrowserRouter([
{
path: '/',
loader: async () => {
await ready;
return redirect(`/${i18n.resolvedLanguage}`);
},
},
{
path: '/:lang',
loader: async ({ params }) => {
if (!SUPPORTED.includes(params.lang)) throw redirect('/en');
await i18n.changeLanguage(params.lang);
return null;
},
HydrateFallback: () => null,
Component: Outlet,
children: [{ index: true, Component: Home }],
},
]);

Render it with <RouterProvider router={router} />, imported from react-router/dom. Because the loader awaits changeLanguage, the locale file is loaded before the route renders. HydrateFallback is what React Router shows while the first loader runs.

The language switch is a navigation to the same path under another prefix:

jsxjsx
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router';
import { SUPPORTED } from './i18n';
export function LanguageSwitch() {
const { t } = useTranslation();
const { lang } = useParams();
const { pathname, search } = useLocation();
const navigate = useNavigate();
return (
<select
aria-label={t('language.label')}
value={lang}
onChange={(event) =>
navigate(pathname.replace(`/${lang}`, `/${event.target.value}`) + search)
}
>
{SUPPORTED.map((code) => (
<option key={code} value={code} lang={code}>
{new Intl.DisplayNames([code], { type: 'language' }).of(code)}
</option>
))}
</select>
);
}

Intl.DisplayNames prints each language in its own name: English, русский, العربية. The languageChanged listener from Part 5 updates lang and dir, and the detector saves the choice, so / redirects a returning visitor to their language. The root loader awaits ready because detection finishes inside init.


Part 11: right to left, long text and accessibility

Right to left

i18n.dir('ar') returns rtl, and the listener in Part 5 writes it to <html dir>. MDN recommends the dir attribute over the CSS direction property, because direction belongs to the content. CSS written with physical sides does not follow. Logical properties are defined relative to the writing direction:

PhysicalLogical
margin-leftmargin-inline-start
padding-rightpadding-inline-end
left: 0inset-inline-start: 0
text-align: lefttext-align: start

Icons that point somewhere, such as back arrows, need mirroring by hand.

Long text

The W3C's article on text size in translation cites IBM figures: a translated English string of up to 10 characters averages two to three times its length, and one over 70 characters about 1.3 times. Its example is the word "views", which becomes "visualizzazioni" in Italian. Buttons and tab labels are where layouts break. Avoid fixed widths and let text wrap.

Accessibility

  • lang on <html>. WCAG success criterion 3.1.1 requires the page language to be programmatically determined, and screen readers use it to choose pronunciation. A passage in another language takes its own lang, as the <option> elements above do.
  • Attributes are text too. aria-label, title, alt and placeholder go through t() or intl.formatMessage. i18next-cli lint reports hardcoded text in JSX elements and attributes, and FormatJS has the no-literal-string-in-jsx rule.
Set lang and dir from one place, write CSS with logical properties from the start, and put one right to left language and one long language, such as German, in the first batch.
In short

Part 12: bundle size and server rendering

  • Split by locale. With i18next-resources-to-backend, each locales/<lng>/<ns>.json becomes its own chunk, and a visitor downloads one language.
  • Split by namespace. A route asks for its namespace in useTranslation, so admin text is not in the first load.
  • Pre-parse ICU. FormatJS recommends compiling messages to AST with formatjs compile --ast, which skips parsing at run time.
  • Compile or tree-shake. Lingui compiles catalogs ahead of time. Paraglide emits a function per message so unused ones can be dropped.

Server rendering is outside the scope of a Vite single-page app. If you add it, the react-i18next documentation uses one i18next instance per request, created by i18next-http-middleware and passed through I18nextProvider, and hands the loaded translations to the client with useSSR.


Part 13: test components in a locale

Mocking t to return the key is quick and hides every plural and placeholder bug. The documented alternative is a real instance with real files:

tests/Header.test.jsx, Vitest with the jsdom environmentjsx
import { cleanup, render, screen } from '@testing-library/react';
import i18n from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, describe, expect, it } from 'vitest';
import en from '../src/locales/en/translation.json';
import ru from '../src/locales/ru/translation.json';
import { Header } from '../src/Header.jsx';
afterEach(cleanup);
function renderIn(lng, ui) {
const instance = i18n.createInstance();
instance.use(initReactI18next).init({
lng,
fallbackLng: false,
resources: { en: { translation: en }, ru: { translation: ru } },
interpolation: { escapeValue: false },
saveMissing: true,
missingKeyHandler: (lngs, ns, key) => {
throw new Error(`Missing translation: ${lngs} ${ns}:${key}`);
},
});
return render(<I18nextProvider i18n={instance}>{ui}</I18nextProvider>);
}
describe('Header in Russian', () => {
it.each([
[1, '1 непрочитанное сообщение'],
[3, '3 непрочитанных сообщения'],
[5, '5 непрочитанных сообщений'],
[21, '21 непрочитанное сообщение'],
])('uses the right plural form for %i', (count, text) => {
renderIn('ru', <Header name="Ada" count={count} />);
expect(screen.getByText(text)).toBeTruthy();
});
});

Three things make this test strict. createInstance() gives each test its own instance. fallbackLng: false stops English from covering for a missing Russian key. missingKeyHandler, which needs saveMissing: true, throws, so a missing key fails the render with the key name in the message.

For react-intl, wrap the component in IntlProvider and pass onError={(err) => { throw err; }}. A message missing from the locale then fails the test with a MISSING_TRANSLATION error. Without it, the component renders the default message or the id and logs to the console.


Part 14: CI checks

.github/workflows/i18n.ymlyaml
name: i18n
on: [pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx i18next-cli extract --ci
- run: npx i18next-cli status
- run: npx i18next-cli status --unused
- run: npx i18next-cli lint
- run: node scripts/check-locales.mjs
- run: npx vitest run
StepFails when
extract --ciThe locale files are not up to date with the keys in code
statusA language is missing a translation, including a plural suffix that language needs
status --unusedA key in the files is no longer used in code
lintText in JSX is not wrapped in t(), or a placeholder does not match

Run against a Polish file with only _one and _other, status pl listed inbox.unread_few and inbox.unread_many as absent. lint compares {{placeholders}}, $t() references and Trans tags in every language with the primary one. That comparison is a warning by default, so the configuration in Part 9 sets lint.checkTranslationPlaceholders to 'error'.

For react-intl, formatjs verify "lang/*.json" --source-locale en --missing-keys --extra-keys --structural-equality does the same job. Against a file with a renamed variable it reported "Missing variable count in message" and exited with status 1.

If translation happens after merge, move the completeness checks to the release workflow so feature branches are not blocked. Localization as code covers that trade, and React localization CI checks goes deeper on the pipeline.


Part 15: translating the files with AI, and checking the result

A model drafts interface text well. The failures are in the syntax around the text, and most of them are silent. These were reproduced for this guide:

What breaksExampleEffect
Placeholder translated{{name}} becomes {{imię}}The raw {{imię}} is shown to the user
Nesting key translated$t(app.name) becomes $t(aplikacja.nazwa)The invented key is printed as text
Trans tag renamed<bold> becomes <pogrubienie>The tag is shown as literal text
Indexed tag renumbered<5> becomes <4>The markup is lost, or a text child is rendered in its place
English plural shape copiedOnly _one and _other in a Polish fileNo error: _other is used for 3, where Polish needs the few form
Suffix key lostOnly _one survivesThe key itself is printed for other counts
Key translatedinvite_female becomes zaproszenie_femaleThe original key is missing
ICU variable translated{count, plural, ...} becomes {liczba, plural, ...}react-intl reports FORMAT_ERROR and shows the English default
ICU keyword translatedplural becomes liczba mnogaSame: syntax error, English shown
other branch droppedone {...} few {...}Same: other is required

Nothing in an English i18next file says that Polish needs two more keys, so a tool that translates key by key returns the English shape. In ICU the whole plural is one string, and a model can rewrite its keywords. How to translate JSON i18n files with AI covers the general case.

i18next-cli lint compares plural forms as a group, so a tag dropped from one form of a plural passes. This script checks every key on its own, and the suffix set of every language:

scripts/check-locales.mjs, Node.js 22, no dependenciesjs
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
const dir = 'src/locales';
const source = 'en';
const plural = /_(zero|one|two|few|many|other)$/;
const flatten = (node, prefix = '', out = {}) => {
for (const [key, value] of Object.entries(node)) {
const path = prefix ? `${prefix}.${key}` : key;
if (typeof value === 'string') out[path] = value;
else flatten(value, path, out);
}
return out;
};
const read = (locale, file) =>
flatten(JSON.parse(readFileSync(join(dir, locale, file), 'utf8')));
const sorted = (list) => [...new Set(list)].sort().join(' ');
const tokens = (text) =>
sorted([
...(text.match(/\{\{-?\s*[\w.]+/g) ?? []).map((m) => m.replace(/[{\s-]/g, '')),
...(text.match(/\$t\([^,)]+/g) ?? []),
...(text.match(/<\/?[\w-]+/g) ?? []),
]);
const needed = (locale) =>
new Intl.PluralRules(locale).resolvedOptions().pluralCategories;
const problems = [];
for (const file of readdirSync(join(dir, source))) {
const base = read(source, file);
const stems = new Set(
Object.keys(base).filter((k) => plural.test(k)).map((k) => k.replace(plural, '')),
);
const model = (key) => base[key] ?? base[`${key.replace(plural, '')}_other`];
for (const locale of readdirSync(dir).filter((l) => l !== source)) {
const target = read(locale, file);
const report = (key, text) => problems.push(`${locale}/${file}: "${key}" ${text}`);
for (const key of Object.keys(base)) {
if (!plural.test(key) && !(key in target)) report(key, 'is missing');
}
for (const stem of stems) {
for (const form of needed(locale)) {
if (!(`${stem}_${form}` in target)) report(`${stem}_${form}`, 'plural form is missing');
}
}
for (const [key, value] of Object.entries(target)) {
const reference = model(key);
if (reference === undefined) report(key, 'is not a key in the source file');
else if (tokens(reference) !== tokens(value)) report(key, 'placeholders, $t() or tags differ');
}
}
}
problems.forEach((p) => console.error(p));
process.exit(problems.length ? 1 : 0);

Against a deliberately broken Polish file it reported the translated placeholder, the changed $t() key, the renamed tag, the link dropped from one plural form, the two missing suffix keys, the invented key and the missing key. A correct Russian file passed. It has limits. It flags a plural form that spells the number out without {{count}}, it expects every CLDR category, including the French _many most files omit, and it cannot see meaning. Automated localization QA lists what a machine can check and what needs a person.

When you prompt a model yourself, send values and write the answers back by key, so it never sees a key to translate. Generate the target language's suffix keys first, with i18next-cli extract, and ask for one translation per key.
Rule
A cream paper-pulp sorting tray on a stone plinth with a row of small paper cards standing in slots, one slot empty and one card lying flat in front
Every key, placeholder, tag and plural suffix is compared with the source before a file is merged

Doing this with Transglot

Transglot is a continuous localization platform. Glossa, its translation engine, translates the strings that changed, and four quality checks run on every string before it is written: placeholders, plural forms, glossary terms and length. A string that still fails the placeholder, plural or glossary check after one repair is refused and reported, not written.

i18next and react-intl files are read as json_nested or json_flat. From the project root, with Node.js 22 or later:

bashbash
npx transglot@latest init --targets ru,ar

init finds the locale files, works out the source language, signs in through the browser, runs the first translation and writes transglot.json:

transglot.jsonjson
{
"url": "https://api.transglot.ai",
"sources": [
{ "path": "src/locales/{locale}/translation.json", "format": "json_nested", "locales": ["en"] }
],
"pull": [
{ "path": "src/locales/{locale}/translation.json", "format": "json_nested" }
]
}

After that, transglot push --wait uploads changed strings and waits for the translation, and transglot pull writes the target files. Add one rule per namespace file. The configuration reference explains each field, and the GitHub Action runs the same round trip on every push to main.

What the documentation says, and does not say, for a React project:

  • Placeholders and tags are checked. The formats page lists double braces such as {{name}}, single braces such as {name}, and HTML tags among the syntaxes the placeholder check recognizes. Values are written back exactly as they are.
  • $t() and numbered Trans tags are not in that list. Do not assume $t(app.name) or <1> is protected. Keep i18next-cli lint or the script above in CI.
  • Suffix keys are ordinary keys. unread_one and unread_other are translated as two separate strings. The JSON page says to add the suffixes a target language needs, such as unread_few, as keys of their own, and the plural check does not apply to them. i18next-cli status is the check for that.
  • An ICU plural in a JSON value is one string. The checks read it as ICU when the project's Message syntax setting says so. See plural forms.
  • Untranslated keys are left out of a pulled file, so fallbackLng and the missing-key checks keep doing their jobs.

The runtime SDKs load published translations from the Transglot CDN while the app runs. Three packages matter for React, and one name is easy to confuse:

PackageWhat it isLimits in the documentation
@transglot/i18next-backendA backend plugin for i18next 23 or later. t() and Trans call sites stay as they arePass authIn: 'query' in a browser. The CDN does not answer CORS preflight requests, so a later read of a locale already loaded, such as a namespace loaded on demand, fails in a browser. namespaceMode: 'perNamespace' maps top-level keys to namespaces
@transglot/react-intlA loader, not a provider: loadMessages() returns the flat messages map for IntlProviderNeeds react-intl 6 or later. Each call is a fresh request with no cache. With ICU message syntax, a translation that is not valid ICU is left out of the bundle
@transglot/react-i18nTransglot's own provider, useTranslations() and T, for React 18 and 19Loads after mount, so there is no server rendering. Use it instead of i18next, not with it
@transglot/reactThe in-context editor for reviewersNot a runtime SDK

No package falls back to another locale on its own, and a CDN key in a browser bundle is visible to anyone, though it only reads what you published. Runtime delivery, the CLI, the GitHub Action and the API start on the Starter plan, at $19 a month for 300,000 translated words. The Free plan works in the browser console only. Transglot is not self-hostable. See pricing.

Other platforms read these files too. Locize is built by the i18next maintainers and has commands in i18next-cli, and the FormatJS CLI ships formatters for Crowdin, Lokalise, Smartling and Transifex. Test any of them on a four-form plural and a Trans string first.


Common mistakes

  • No fallbackLng. i18next 27 has no default, so a missing key prints its own name.
  • Calling a plural key without count. t('inbox.unread') looks up a key that does not exist.
  • Shipping only _one and _other to every language. Russian, Polish and Arabic get the wrong form with no error.
  • Sentences built from pieces. Use one key with placeholders, or Trans for markup.
  • Indexed Trans tags in files sent to translators. Use named components.
  • No Suspense boundary with a lazy backend. The app renders blank while a namespace loads.
  • Mocking t in every test. The mock passes whatever the file contains.
  • Physical CSS sides. margin-left does not flip under dir="rtl".

Checklist

texttext
[ ] Library chosen by message style: i18next JSON or ICU
[ ] i18next and react-i18next installed, init called once with fallbackLng
[ ] One JSON file per language and namespace, every string read through t()
[ ] Plural keys for every CLDR category of every target language
[ ] Whole sentences in every plural form
[ ] Markup inside sentences uses Trans with named components
[ ] Dates, numbers, currency, lists and relative time formatted through Intl
[ ] Locale files loaded on demand, Suspense boundary in place
[ ] Language detected, saved, and present in the URL
[ ] lang and dir set on <html>, CSS uses logical properties
[ ] aria-label, title, alt and placeholder translated
[ ] Typed keys through CustomTypeOptions or i18next-cli types
[ ] Component tests use a real instance and throw on a missing key
[ ] extract --ci, status and lint run in CI, placeholder check set to error
[ ] check-locales.mjs runs on translated files
[ ] One right to left language and one four-form language in the first batch

Frequently asked questions

What is the best i18n library for React?

There is no single answer. react-i18next fits apps that want keys, namespaces and plugins for loading and detection. react-intl fits teams that work in ICU MessageFormat. Lingui fits teams that prefer source text in JSX, and Paraglide compiles messages to functions a bundler can tree-shake.

What is the difference between react-i18next and react-intl?

react-i18next uses i18next's JSON format: {{name}} placeholders and one key per plural form, such as item_one and item_other. react-intl uses ICU MessageFormat, where the plural is one message with branches. react-i18next loads files through backend plugins, and react-intl takes a messages object as a prop.

How do I add i18n to a React app?

Install i18next and react-i18next, create an i18n.js that calls i18n.use(initReactI18next).init({ lng, fallbackLng, resources }), and import it once before rendering. In components, call const { t } = useTranslation() and replace text with t('key').

How do plurals work in react-i18next?

Pass count to t() and define one key per plural category with a suffix: key_one and key_other for English. i18next picks the suffix with Intl.PluralRules for the active language. Russian and Polish also need _few and _many, and Arabic needs six keys.

How do I change the language in react-i18next?

Call i18n.changeLanguage('ru'), which returns a promise and loads the language if needed. Components that use useTranslation or Trans render again. With i18next-browser-languagedetector and caches: ['localStorage'], the choice is saved for the next visit.

How do I lazy load translations in React?

Register i18next-resources-to-backend with a dynamic import() of ./locales/${language}/${namespace}.json, or i18next-http-backend to fetch files from /locales. Wrap the app in Suspense, because useTranslation suspends while a file loads.

Do I need the Trans component?

Only when markup or a link sits inside a sentence. For plain strings t() is enough. Trans keeps the sentence as one translatable string and maps tags in it to React elements you pass in components.

Can I use AI to translate i18next JSON files?

Yes, with checks. A model can translate {{name}}, rewrite $t() keys, rename Trans tags, and return only the English _one and _other keys for a language that needs four. Compare every key with the source and check the suffix set per language before merging.

How this guide was checked

  • Setup, useTranslation, Trans, namespaces, testing, server rendering and the version 18 changes follow the react-i18next documentation. Interpolation, plurals, context, nesting, formatting, fallback, configuration options, typed keys and extraction follow the i18next documentation. The detector, the two backends and i18next-parser follow their READMEs.
  • status, lint, extract, types and the CI steps follow the i18next-cli pages. The react-intl parts follow the FormatJS documentation for react-intl 12, the ICU syntax page and the CLI page. Lingui and Paraglide statements are from their own sites and were not run.
  • Run for this guide with Node.js 22 under Vitest 5 and jsdom: both init files, every row of the message format table, escaping on and off, the Russian plural forms, the Trans sample, the react-intl components and formatters, the React Router loaders and language switch with a memory router, including a cold start at / with a saved language, the missing-key test for both libraries, the typed-key error with TypeScript 7.0, i18next-cli status and lint, formatjs extract, verify and compile, every row of the AI failure table, and scripts/check-locales.mjs against a correct Russian file and a broken Polish file.
  • Not run: i18next-http-backend, a real Vite production build, createBrowserRouter in a real browser, the server rendering note, the CI workflow, the Transglot commands and the Transglot runtime packages. The "indexed tag renumbered" row of the AI table follows the i18next-cli lint page.
  • The plural categories are those Intl.PluralRules returned in Node.js 22. Text expansion figures are from the W3C article, and the lang and dir statements from MDN.
  • No translation platform was benchmarked. Transglot statements follow the Transglot documentation, including the limits listed in that section.

Sources

colophon

Who wrote this, and what to read next

wrote this

transglot team

The byline on this post has no profile yet. Author profiles are managed alongside the posts themselves.

Engineering
keep reading

i18next best practices for scalable apps

Scale i18next with deliberate namespaces, correct plural lookups, safe interpolation and explicit fallback rules. Includes working examples and a release checklist.

February 3, 2026
6 min read
keep reading

React localization: check keys, variables and plurals

Build a small React localization workflow with i18next. Catch missing keys, renamed variables and plural errors before deployment with a Node.js CI check.

November 9, 2026
10 min read
keep reading

How to Translate a React or Next.js App Automatically

The three parts of automatic translation in a React or Next.js app, the tools that cover each part, and a setup that keeps every language current on each push.

November 23, 2026
8 min read
works with what you already run

41 connectors, already built.

the pipeline this post describes

Try it on your own strings. Free, no card.

Free plan: 100,000 words to start (25,000 at sign-up, 75,000 after a phone check), then 10,000 a month, 15 locales including your source, 3 seats.