How to automatically update app language
This example demonstrates how to automatically update app language using the useLang
hook.
tsx
import { useLang } from "./useLang";
const translations = {
en: {
title: "Latest News",
content: "Stay updated with the latest happenings around the world.",
},
es: {
title: "Últimas Noticias",
content: "Mantente al día con los últimos acontecimientos en el mundo.",
},
};
export default function App() {
const lang = useLang();
const currentLang = lang.startsWith("es") ? "es" : "en";
return (
<>
<h1>{translations[currentLang].title}</h1>
<p>{translations[currentLang].content}</p>
</>
);
}
typescript
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);