useLang
React hook to detect the language selected in the browser.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useLangsh
npx @novajslabs/cli add useLangsh
pnpm dlx @novajslabs/cli add useLangOr copy and paste the code into your project:
ts
import { useSyncExternalStore } from "react";
const langSubscribe = (cb: () => void) => {
window.addEventListener("languagechange", cb);
return () => window.removeEventListener("languagechange", cb);
};
const getLang = () => navigator.language;
export const useLang = (): string =>
useSyncExternalStore(langSubscribe, getLang);js
import { useSyncExternalStore } from "react";
const langSubscribe = (cb) => {
window.addEventListener("languagechange", cb);
return () => window.removeEventListener("languagechange", cb);
};
const getLang = () => navigator.language;
export const useLang = () => useSyncExternalStore(langSubscribe, getLang);Requirements
React 18.0 or higher
Return values
lang
Type: string
The code of the language selected in the user's browser ("es", "en", "it", "fr", etc.).