Skip to main content

LanguageContext

LanguageContext manages the application's active language, text direction (LTR/RTL), and the Emotion CSS cache (which must be swapped between ltr/rtl variants for MUI to generate correct CSS).

Import

import { LanguageProvider, useLanguage } from "@xocialive/ui-components/contexts";
import type { LanguageContextProps } from "@xocialive/ui-components/contexts";

useLanguage()

const { language, direction, isRTL, changeLanguage } = useLanguage();
ValueTypeDescription
languagestringCurrent language code (e.g. "ar", "en")
direction"ltr" | "rtl"Derived from the language code
isRTLbooleantrue when language starts with "ar"
changeLanguage(lang: string) => voidUpdates language, persists to localStorage, writes both "language" and "i18nextLng" keys

Controlled mode (i18next integration)

Pass language and onLanguageChange to drive the context from i18next:

import i18n from "./i18n";

<LanguageProvider language={i18n.language} onLanguageChange={(lang) => i18n.changeLanguage(lang)}>
<App />
</LanguageProvider>;

In controlled mode the provider does not write to localStorage — it just mirrors the external source.

Default value (without a provider)

The context default reads localStorage at module initialisation time so components that render outside a LanguageProvider (e.g. in tests or static previews) still receive the correct language rather than always falling back to "en".

Emotion caches

The provider transparently swaps Emotion's CacheProvider:

  • RTL — cache keyed "muirtl" with prefixer + rtlPlugin (stylis)
  • LTR — cache keyed "mui" with no plugins

This means all MUI components automatically receive correct RTL CSS when isRTL is true. You do not need to configure this manually.

readStoredLanguage()

An exported utility that reads the active language from localStorage synchronously, compatible with both the library's own key and i18next's i18nextLng key:

import { readStoredLanguage } from "@xocialive/ui-components/contexts";

const lang = readStoredLanguage(); // "ar" | "en" | ...