When I change the route or reload the page then the language resets.
On the console I get this log message:
i18next: languageChanged en
I think it happens due to this call:
const { i18n } = useTranslation();
How can I tell it to use the locale I stored (let's say in the variable locale
) instead of guessing all over again?
on component mount update the locale then use the same.
function LanguageSelector() {
const { i18n } = useTranslation();
// Load the saved locale from localStorage or use a default value
const savedLocale = localStorage.getItem('locale') || 'en';
// Set the initial language when the component mounts
useEffect(() => {
i18n.changeLanguage(savedLocale);
}, [i18n, savedLocale]);
const changeLanguage = (language) => {
// Save the selected locale to localStorage
localStorage.setItem('locale', language);
// Change the language
i18n.changeLanguage(language);
};
return (
<div>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('es')}>Español</button>
</div>
);
}