useLocale React hook in TypeScript
v1.0.0Added in 1.0.0
A React hook for the locale numbers, dates and prices are formatted with, the same on the server and in the browser.
The card formats one price, one date and one count with the resolved locale. Leave the locale empty to follow the page and the browser (after hydration), or pick one to see a component's own locale prop win. The provider example pins de-DE for everything inside it, on the server too.
useLocale is a free React hook in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add use-locale.
Add to a project
Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup
npx wingo-ui@latest add use-localeUsage
Import useLocale from @/hooks/use-locale.
import { LocaleProvider, useLocale } from "@/hooks/use-locale"
export function Price({ value, locale }: { value: number; locale?: string }) {
const resolved = useLocale(locale)
return <span>{new Intl.NumberFormat(resolved, { style: "currency", currency: "USD", currencyDisplay: "narrowSymbol" }).format(value)}</span>
}
export function App({ children }: { children: React.ReactNode }) {
// everything inside formats as en-GB, on the server and in the browser
return <LocaleProvider locale="en-GB">{children}</LocaleProvider>
}API
localedefault""stringuseLocale(locale?): a component's own locale prop, which wins when set. Empty falls back to the nearest LocaleProvider, then (after hydration) <html lang> and the browser's language.
returnsstringA canonical BCP 47 tag. On the server and during hydration it is the provider's locale or DEFAULT_LOCALE ("en-US"), so both renders print the same text; the browser's language arrives right after.
Parts
LocaleProvider
componentPins the locale for everything inside it, on the server too, so nothing swaps after hydration. Put one in the root layout of a Romanian app. Props: ({ locale: string; children }) => JSX.Element.
getBrowserLocale
functionThe page's lang, then navigator.language, for code outside React (event handlers). DEFAULT_LOCALE is the server fallback. Signature: () => string.
DEFAULT_LOCALE
constantThe fallback locale, "en-US", used on the server and during hydration when no prop or provider sets one.
Examples
One provider per storefront
The same order card under an en-US and an en-GB LocaleProvider: dates and separators follow, the server render matches.
A component's own locale wins
Inside an en-US provider, the second card passes locale="fr-FR" and useLocale returns it first.
Dependencies
No dependencies beyond React.
Files
- hooks/use-locale.ts
FAQ
Is the useLocale hook free?
Yes. The source is free and needs no account: copy it from the Code tab or install it with the CLI.
How do I install useLocale?
Run npx wingo-ui@latest add use-locale. With shadcn, run npx shadcn@latest add https://wingo-ui.com/r/use-locale.json.