Skip to content

useLang

React hook to detect the language selected in the browser.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useLang
sh
npx @novajslabs/cli add useLang
sh
pnpm dlx @novajslabs/cli add useLang

Or 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.).

Examples of common use cases