usePreferredLanguage

Manages and resolves the application language based on system settings and user overrides.

Important

This hook synchronizes the user's language preference across all open browser tabs using localStorage and the event.

Note

The language value follows the BCP 47 standard (e.g., 'en-US', 'es-PE'). Ensure your localization dictionary supports these specific codes or includes a fallback mechanism.

Installation

bash

Description

A robust language management hook that looks for a user-defined preference in localStorage. If no user preference exists, it falls back to the system/browser language. It handles cross-tab synchronization and is safe for SSR.

Return values

NameTypeDescription
languagestringThe active language code (User selection or System fallback).
setUserLanguage(lang: string) => voidFunction to update and persist the user's preferred language.
systemLanguagestringThe default language detected from the browser.
userLanguagestring | nullThe specific language saved by the user, if any.

Demo

Preferred Language

System: enUser: en
Resolved Language: en

Source code

tsx