Problem
When the translation language is changed I also change the moment.js locale for my time-series charts in Chart.js. I need a way to detect language changes so I can rerender the charts.Solution
Add the locale ISO code into the translation files and use that.What I did was:
- Add a new translation key in my translation files: 'current_locale': 'en' for the English translation, 'current_locale': 'ro' for Romanian.
- Use the useTranslation() hook:
const { t } = useTranslation(); - Rerender the chart when language is changed:
useEffect(() => { // This will be now called when the locale is changed }, [t('current_locale')])
Improvements
You can also create a custom hook if you want:export const useLocale = () => {
const { t } = useTranslation();
return t('current_locale');
};
Now you can use the locale value directly:const locale = useLocale();
useEffect(() => {
// This will be now called when the locale is changed
}, [locale])

Self-hosted analytics
There's a cleaner solution:
ReplyDeleteconst { i18n } = useTranslation();
// Then use the i18n.language you don't need to store any key anywhere
useEffect(() => {
// This will be now called when the locale is changed
}, [i18n.language]);
Thanks for pointing this out!
DeleteDo you know if it was always there or was it introduced recently? I remember that I searched for something like this but couldn't find it at the time of writing this post.