Learn how to generate multi-language images in seconds with Bannerly!See Bannerly.io

How to use code splitting with JSON files in React application

How to use code splitting with JSON files in React application

Code-splitting for resources

Code-splitting is a built-in function in many code bundlers like Webpack. It's used mostly to lazy load only required JavaScript code or other resources. It helps in improving application performance by loading only required parts of the application instead fetching all resources at once. This is a perfect solution for localization purposes to load translations for only one language instead for all of them to speed up your web application.

Medium-sized web application with about 1000 unique translation keys can contain about 50kb translated messages for one language. If you would support 10 languages in your app, whole translation file could have size nearly 1 megabyte.

Learn more about code-splitting in React.

How to lazy load JSON file in React?

Here is the asynchronous function TypeScript, which accepts languageKey as a string and returns loaded JSON file as an JavaScript object.

const loadJson = (languageKey: string): Promise<any> => {
  return new Promise((res, rej) => {
    import(`../assets/i18n/${languageKey}-messages.json`).then((data) => {
      res(data?.default);
    });
  });
};

How to use lazy load in React app?

Here is the full example code for lazy loading translations from local JSON files. Code is written in TypeScript however it should be easy to convert into plain JavaScript.

import {useState} from "react";

const [locale, setLocale] = useState('en-US');
const [messages, setMessages] = useState({});

// first useEffect
useEffect(() => {
  const locale = window.navigator.language;
  setLocale(locale);
}, []);

// second useEffect
useEffect(() => {
  loadJsonAsync = async () => {
    const messages = await loadJson(locale);
    setMessages(messages);
  }
  loadJsonAsync();
}, [locale])

// use your messages

React will invoke:

  • the first useEffect hook only once on every page re-render. We are getting the language from web browser. Learn more about navigator.language object.

  • the second useEffect hook when locale value is changed in order to lazy load different JSON file with translations.

You cannot invoke async functions in useEffect React hook, that is why we create a new loadJsonAsync function.

Check example how to load translations from backend using a standard fetch API.

Use loaded JSON messages with IntlProvider

To use loaded JSON messages with FormatJS you can simply pass locale variable and messages object as props to IntlProvider.

<IntlProvider 
  locale={locale} 
  messages={messages}
>
          {children}
</IntlProvider>

children variable should contain your React component or even a whole application (eg. <App/>) in which you want to provide translations.


Share article
See all articles
Try SimpleLocalize i18n editor and hosting
localization workflow process

Relevant posts

GitHub Actions is available!

GitHub Actions is available!

Jakub PomykałabyJakubNovember 28, 2021

GitHub Actions integration for Continuous Localization is available on GitHub Market! Connect your GitHub repository to SimpleLocalize i18n editor for free!

Read more
Number formatting in JavaScript

Number formatting in JavaScript

Jakub PomykałabyJakubNovember 28, 2021

Discover power of 'toLocaleString' functions in JavaScript. Format numbers, currencies, and units without any 3rd party localization library.

Read more
How to create a multi-language website in GatsbyJS?

How to create a multi-language website in GatsbyJS?

Jakub PomykałabyJakubAugust 09, 2021

Create a multi-language GatsbyJS website with a few simple steps. A multi-language website is a great way for your company to reach a wider audience.

Read more
List of i18n libraries for React, React Native, and NextJS

List of i18n libraries for React, React Native, and NextJS

Jakub PomykałabyJakubFebruary 12, 2021

Best i18n libraries for React web, React Native, Expo and all other React apps. Check how to react localization should look like.

Read more
i18next and React application localization in 3 steps

i18next and React application localization in 3 steps

Jakub PomykałabyJakubOctober 01, 2020

How to localize ReactJS application with i18next internationalization library. Learn how to manage localization in software project

Read more
Internationalization tool for yahoo/react-intl

Internationalization tool for yahoo/react-intl

Kinga WojciechowskabyKingaJune 26, 2020

Are you struggling with keeping your app translations up to date and your dreams are filled with empty keys to translate? No worries, we know that feeling very well. To make the whole localisation process easier, we created a simple and effective solution which will improve the quality of translations and help you keep them in track!

Read more