#5929·moment

How to dynamically load moment locales with react in a SPA and force a re-render in local env and production?

Author: gazpachuCreated Sep 3, 2021Updated Oct 21, 2024

I'm reposting my question here for people looking for the same answer in the future:

https://stackoverflow.com/questions/69051040/how-to-dynamically-load-moment-locales-with-react-in-a-spa-and-force-a-re-render

I resist the idea of loading the moment locales all at once (in my case 18, 70+KB) and I was wondering what would be the best approach to load them dynamically.

This is what I've got so far, but it has a few caveats:

  • It won't work in production, as there are no node_modules folder in that env. I presume we'll have to put the moment locale JS files in the public folder to be able to load them in production
  • It won't trigger a re-render of the components using dates, so might need a different global state to handle that
const [, { languages }] = useTranslation();

useEffect(() => {
  async function loadMomentLocale() {
    // Requires a switch because dynamic imports don't support string interpolation
    switch (languages[0]) {
      case 'es':
        await import('moment/locale/es');
        break;
      case 'fr':
        await import('moment/locale/fr');
        break;
    }
  }

  if (languages) {
    loadMomentLocale().then(() => moment.locale(languages[0]));
  }
}, [languages]);