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

Example

tsx
import { useLang } from "./hooks/useLang";

const App = () => {
  const lang = useLang();

  return <p>Your selected language is {lang}</p>;
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Synchronizing the language preference of a web application with the browser's language settings
  • Updating the UI language dynamically based on changes made in the browser's language settings
  • Reacting to changes in the user's preferred language to provide localized content in real-time
  • Automatically adjusting language-dependent features such as date formats or translations in response to language changes
  • Enabling seamless integration with browser language settings to deliver a personalized user experience

Released under the MIT License.