Skip to content

useLocale returns locale from path params instead of provider value in client components #688

Description

@cbodin

Description

useLocale will always return the locale path parameter in client components even though NextIntlClientProvider is configured with a hard-coded locale.

I cannot find anything related to this behaviour in the documentation so this should probably be documented and/or add an option to useLocale to retrieve the locale from the provider and not the path parameters for client components.

// The types aren't entirely correct here. Outside of Next.js
// `useParams` can be called, but the return type is `null`.
const params = useParams() as ReturnType<typeof useParams> | null;
if (typeof params?.[LOCALE_SEGMENT_NAME] === 'string') {
locale = params[LOCALE_SEGMENT_NAME];
} else {
// eslint-disable-next-line react-hooks/rules-of-hooks -- Reading from context conditionally is fine as long as we're in the render phase
locale = useBaseLocale();
}

Mandatory reproduction URL (CodeSandbox or GitHub repository)

https://codesandbox.io/p/devbox/next-intl-bug-template-app-forked-w4q7qq

Reproduction description

  1. Open up the /_next/info page and view the resulting locales.
  2. Open up the /en/info page and view the resulting locales.
  3. Remove the notFound(); call in src/app/[locale]/layout.tsx.
  4. Open up the /_next/info page and view the resulting locales.

Expected behaviour

The universal "useLocale" hook should return the expected locale configured in the provider in client components.
All displayed locales should be "en" in client components.

This ensures that components can be re-used in 404:s from _next/* paths.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingunconfirmedNeeds triage.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions