# React

Source: https://verbaly.dev/docs/frameworks/react

The official React 18/19 package for Verbaly. Hooks over the same reactive core, a compiler-aware \<Trans> for rich text, and keys + params fully typed.

What you can accomplish:

- Translate with hooks (useT, useLocale) that re-render exactly when the language changes
- Write rich text in place: the compiler extracts `<Trans>` children like any `` t`…` ``
- Keep keys and params fully typed, with autocompletion from your own messages
- Concurrent-safe by construction: subscriptions ride on `useSyncExternalStore`
- Use it in Preact through `preact/compat`, with no extra package

## Installation

Add the runtime, this package and the Vite plugin, then the compiler, which is where the `verbaly` command lives. `init` writes your config and your source catalog.

```sh
npm install verbaly @verbaly/react @verbaly/vite
# or: pnpm add verbaly @verbaly/react @verbaly/vite
# or: yarn add verbaly @verbaly/react @verbaly/vite
# or: bun add verbaly @verbaly/react @verbaly/vite
```

```sh
npm install -D @verbaly/compiler
# or: pnpm add -D @verbaly/compiler
# or: yarn add -D @verbaly/compiler
# or: bun add -D @verbaly/compiler
```

```sh
npx verbaly init
```

Then add `verbaly()` to the plugins in `vite.config`. It writes `verbaly/app`, the module your components read.

On webpack, Rollup, esbuild or Rspack, install `@verbaly/unplugin` in place of `@verbaly/vite`: [other bundlers](https://verbaly.dev/docs/frameworks/vite.md#unplugin) shows how.

## Setup & hooks

```tsx title="App.tsx"
import { VerbalyProvider, useT, useLocale } from '@verbaly/react';
import { verbaly } from 'verbaly/app';

<VerbalyProvider instance={verbaly}>
  <App />
</VerbalyProvider>

function Inbox({ count }) {
  const t = useT();
  const [locale, setLocale] = useLocale();
  return <p>{t`You have ${count} messages`}</p>;
}
```

- Re-renders via `useSyncExternalStore`: safe with concurrent rendering and on a server.
- `useVerbaly()` exposes the full instance when you need it.
- No provider above a component in the browser? `useT()` and `useLocale()` read the instance `verbaly/app` creates, and the bundler plugin loads that module in every file that imports `@verbaly/react`, so a single-page app or a component test needs no wrapper. On a server the provider is required, since each request has its own instance.
- `useT()` hands out a new `t` when the language changes, so a `useMemo` or an effect keyed on it follows; while nothing changes, it stays the same function.

### The language a visitor picks

`setLocale` from `useLocale()` switches every component, and the page follows: `<html lang>`, `<html dir>` and the choice, saved in the browser. A single-page app starts in its source language, so read that choice back before the first render:

```tsx title="main.tsx"
// the saved choice, else the browser's, loaded before anything renders
import { resolveLocale } from 'verbaly';
import { locales, setLocale } from 'verbaly/app';

setLocale(resolveLocale({ supported: locales, path: false })).then(() => {
  createRoot(document.getElementById('root')!).render(<App />);
});
```

Where a server renders the page, as in Next.js, switch with `useSwitchLocale` from `@verbaly/next/client` instead: it also sets the cookie the server reads.

### Write the text in place

The compiler reads your `.tsx` files: write the source text with `t` and it is extracted, keyed and typed on save. No key to invent, no catalog to touch.

```tsx title="Inbox.tsx"
<p>{t`You have ${count} messages`}</p>

// extracted on save; the build rewrites it to:
<p>{t('nUDFBXR5', { count })}</p>
```

Prefer readable keys? `t.id('inbox.title')` before the template extracts under your id instead of a content hash.

Prefer to keep the text in your catalog? Write only its key: it is checked and typed the same way. See [Keys and catalogs](https://verbaly.dev/docs/guide/keys.md).

### Rich text with \<Trans>

Write the source text in place and the compiler extracts it, exactly like `` t`…` ``:

```tsx title="Agree.tsx"
import { Trans } from '@verbaly/react';

// you write:
<Trans>Read the <a href='/terms'>terms</a> before continuing</Trans>

// the compiler extracts "Read the <a>terms</a> before continuing" and rewrites to:
<Trans id='x7Ka9q2f' components={{ a: <a href='/terms' /> }} />
```

- Child attributes are preserved; params (`{count}`) become `values`; nesting works; unknown tags fall back to inner text.
- Allowed tags render for real: `<em>`, `<code>` and friends in a message become real elements, the same safe list as plain HTML. `richTags` overrides the list; an empty list flattens tags back to plain text.
- Readable keys: write `<Trans id="inbox.title">…</Trans>` with children and it extracts under that id instead of a hash.
- Runtime-first still works: pass `id` without children (or with your own `values`/`components`) and the compiler leaves the element untouched.
- JSX whitespace rules apply: a line break between an element and text renders no space; use the `{' '}` idiom, extraction stays faithful to what React renders.
- Named links: the `links` prop maps tag names to hrefs: `<docs>…</docs>` renders as a real `<a>` without a custom component. `components` wins over `links` on the same name; `javascript:` hrefs are blocked.
- No provider? Pass the `instance` prop and `<Trans>` renders straight from it, re-rendering on every language switch.
- Both forms type-check: children in your source, `id` at runtime. A `<Trans>` the compiler never saw, with no plugin or in a file outside `include`, renders its children as written, like an uncompiled `` t`…` ``.
- In a React Server Component, import `Trans` from `@verbaly/react/server`: it renders from the `instance` you pass, with no provider and no hooks. In Next.js, `@verbaly/next/server` exports one that finds the request's instance itself.

## Next.js

Server Components render already translated in the visitor's language, and Client Components start with the same language and catalog: no flash of untranslated text, no mismatch between server and browser.

- Every page renders in the visitor's language, taken from the address when it carries one, and otherwise from their saved choice or `Accept-Language` header
- No flash of untranslated text: the HTML the server sends and the page after hydration are identical, catalog included
- Each request gets its own instance, so simultaneous visitors never see each other's language
- Turbopack and webpack, both fully supported: the `t` compiler runs as a loader on either bundler, on exactly the files `verbaly extract` reads

Next.js needs the integration (`@verbaly/next`) alongside the React package and the compiler:

```sh
npm install verbaly @verbaly/next @verbaly/react
# or: pnpm add verbaly @verbaly/next @verbaly/react
# or: yarn add verbaly @verbaly/next @verbaly/react
# or: bun add verbaly @verbaly/next @verbaly/react
```

```sh
npm install -D @verbaly/compiler
# or: pnpm add -D @verbaly/compiler
# or: yarn add -D @verbaly/compiler
# or: bun add -D @verbaly/compiler
```

```sh
npx verbaly init
```

## Wire it up

Wrap your config with `withVerbaly`. It wires live extraction in dev and the message compiler on Turbopack and webpack. Once `next build` has compiled, it lists what `verbaly check` would fail on, so a command that only loads your config, like `next typegen`, never meets that report:

```ts title="next.config.ts"
import { withVerbaly } from '@verbaly/next';

export default withVerbaly({ /* your Next config */ });

// locales live in your verbaly.config (npx verbaly init), where verbaly check reads them too
```

In the root layout, `getVerbalyProps` serializes the negotiated language and its catalog, and `VerbalyProvider` seeds the client from them:

```tsx title="app/layout.tsx"
import { getRequestLocale, getVerbalyProps } from '@verbaly/next/server';
import { VerbalyProvider } from '@verbaly/next/client';
import { localeDirection } from 'verbaly';

// the language comes from the cookie and Accept-Language, so the shell renders per request
export const instant = false;

export default async function RootLayout({ children }) {
  const locale = await getRequestLocale();
  const props = await getVerbalyProps();
  return (
    <html lang={locale} dir={localeDirection(locale)}>
      <body>
        <VerbalyProvider {...props}>{children}</VerbalyProvider>
      </body>
    </html>
  );
}
```

`export const instant = false` is for `cacheComponents`, which `create-next-app` turns on: a layout that reads the request outside `<Suspense>` fails the build there, and a language chosen by cookie is exactly that. Without `cacheComponents`, leave the line out. To keep pages static instead, put the language in the address, below.

## Server and Client Components

Server Components get a request-scoped `t` with `await getT()`, resolved once per request (the address first when it carries the language, then the cookie, then `Accept-Language`, then your fallback):

```tsx title="app/page.tsx"
import { getT } from '@verbaly/next/server';

export default async function Page() {
  const t = await getT();
  return <h1>{t`Welcome back`}</h1>;
}
```

Rich text in a Server Component is the same `<Trans>` as in React, from `@verbaly/next/server`: it renders in the request's language with no provider.

```tsx title="app/page.tsx"
import { Trans } from '@verbaly/next/server';

<Trans>Read the <a href="/terms">terms</a> before you go on</Trans>
```

Outside a page, where there is no request to read (an OG image, a sitemap, an email), name the language. That call never reads the request, so the route stays static:

```ts title="app/og/route.ts"
import { getT } from '@verbaly/next/server';

export async function GET() {
  const t = await getT({ locale: 'es' });
  return Response.json({ title: t('home.lead') });
}
```

With `routing: 'no-prefix'`, a share card can mix two languages: a crawler reads the page in the language it negotiates, while an image that names its language is always in that one. To keep them together, give each language its own url with a prefix routing mode. Or let the image read the request like the page does, with `getT()` and no language, which renders it on every request.

Client Components use the React hooks, re-exported from `@verbaly/next/client`:

```tsx title="Counter.tsx"
'use client';
import { useT } from '@verbaly/next/client';

export function Counter() {
  const t = useT();
  return <p>{t`You have new messages`}</p>;
}
```

Keys are typed: `getT()` and `useT()` check every key and its params against your catalog, and `getRequestLocale()` returns one of your languages. The types live in `.verbaly/types.d.ts`, next to the generated modules and never committed. TypeScript skips a dot folder, so Verbaly adds that file to the `include` of your `tsconfig.json`, the way Next adds `.next/types`. On a fresh clone, `next typegen && tsc --noEmit` writes them before it checks them.

> **Why hydration never flashes**
>
> The server negotiates once per request (through React `cache()`). The provider receives the language and its catalog as serialized props, and the client seeds its instance from them synchronously, without downloading that catalog a second time. Both sides produce identical HTML, so nothing repaints and nothing mismatches.

## The language in the address

If your pages live under `app/[locale]/`, say so in your config first: `routing: 'prefix-all'` gives every language its own segment. That line is what gives `getAlternates` the other languages and sends `useSwitchLocale` to the new address, and without it `setRequestLocale` warns once, since the segment and the config would contradict each other.

```ts title="verbaly.config.ts"
export default {
  locales: ['en', 'es', 'pt'],
  routing: 'prefix-all',
};
```

Then hand Verbaly the segment. On Next 16.3 and later there is nothing to write: with the segment in your root layout, Verbaly reads it by itself in every layout, page and `'use cache'` function. **Your page is built ahead of time**, and the address decides the language for everyone who opens the link. On Next 15 up to 16.2, call `setRequestLocale` in every layout and every page of the tree, and pass the language to `getT` inside `'use cache'`: Next can render a page without running its layout, and a page that finds no language reads the cookie instead of the address.

```tsx title="app/[locale]/layout.tsx"
import { setRequestLocale, getVerbalyProps, getAlternates } from '@verbaly/next/server';
import { locales } from 'verbaly/app';

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export async function generateMetadata({ params }) {
  const { locale } = await params;
  return { alternates: getAlternates({ path: `/${locale}`, baseUrl: 'https://example.com' }) };
}

export default async function LocaleLayout({ children, params }) {
  const { locale } = await params;
  setRequestLocale(locale);  // Next 15 to 16.2: in every layout and page
  return <VerbalyProvider {...(await getVerbalyProps())}>{children}</VerbalyProvider>;
}
```

`getAlternates` hands `generateMetadata` the address of this page in every language plus the canonical, which is what tells a search engine that your translations are the same page and not duplicates. It is the same set a statically rendered site gets.

Those addresses, and the one `useSwitchLocale` navigates to, follow `trailingSlash` in your `next.config`. Next never ends an address in a slash unless you ask it to, so the Spanish home is `/es`.

## Switching languages

`useSwitchLocale` follows your routing. When the address carries the language, it moves to the same page in the new language through the app router. When it does not, it switches the client live, writes the cookie the server reads, and re-renders Server Components through `router.refresh()`:

```tsx title="LangPicker.tsx"
'use client';
import { useSwitchLocale } from '@verbaly/next/client';

export function LangPicker() {
  const switchLocale = useSwitchLocale();
  return <button onClick={() => switchLocale('es')}>Español</button>;
}
```

- The cookie defaults to `verbaly-locale` (same identity as the core's storage key); `cookie: false` in the options disables it, for pure `Accept-Language`.
- `fallback` defaults to your source language; negotiation follows the order of preference of the browser, and `es-PE` matches `es`.
- `next build` lists missing, broken and unknown keys once it has compiled, with the exact keys to fill, and finishes, under Yarn PnP too. `failOnMissing: true` stops it there instead, printed once above Next's own failure line.
- `liveExtraction: false` keeps `next dev` from writing your translation files: new texts render from memory, as in a build, and `npx verbaly extract` writes them when you choose.
- `withVerbaly` keeps a `compiler.runAfterProductionCompile` hook of your own and runs it first. A wrapper applied outside `withVerbaly` that replaces that hook instead of calling it would switch off the build report, so keep `withVerbaly` outermost.
- Dev and build show the same words: a text written in your code wins over a hand edit of it in the catalog in both. In dev, the terminal says what would otherwise happen quietly: that replaced edit, a key written with two texts, a translation now older than its source. Each one once, and again if it comes back; a long list stays a few lines, and a catalog saved half-typed pauses live extraction with a one-line reason instead of a stack trace.
- `next dev`, `next build` and `next typegen` say once, when they start, if a file outside your `include` writes `` t`…` ``, which no build translates: in a project without `src/`, add `components/` there.
- Reading request headers is what makes a page render on every visit, so pass the `[locale]` segment and it stops happening. For a site with no server at all, prefer pre-translated output per language with [verbaly render](https://verbaly.dev/docs/reference/cli.md).
