Manage locales with useLocales and getClientLocales
mainYou can manage user locales using a combination of server-side detection and client-side consumption.
- Server-side: Use
getClientLocales(request)in your root loader to extract locales from the request or headers. Conventionally, return an object with alocaleskey. - Client-side: Use the
useLocales()hook to access these locales. The return type isLocales(string | string[] | undefined), which is compatible with the standardIntlAPI.
import { useLocales } from "remix-utils/locales/react";
import { getClientLocales } from "remix-utils/locales/server";
// in the root loader
export async function loader({ request }: Route.LoaderArgs) {
let locales = getClientLocales(request);
return json({ locales });
}
// in any route (including root!)
export default function Component() {
let locales = useLocales();
let date = new Date();
let dateTime = date.toISOString;
let formattedDate = date.toLocaleDateString(locales, options);
return <time dateTime={dateTime}>{formattedDate}</time>;
}