React hook to detect the language selected in the browser.

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)

React 18.0 or higher

  • Name

    The code of the language selected in the user's browser. ("es", "en", "it", "fr", etc.)

import { useLang } from './hooks/useLang'

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

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

export default App

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