Dictionaries

How to use dictionaries

Overview

Dictionaries are a way to translate string content in General Translation. All content is stored in a central file and can be accessed using the useDict() hook.

If you've used other i18n libraries, you may be familiar with using translation files (en.json, zh.json, etc.). Using dictionaries basically syntactically identical except that you only need to maintain one file in your base language. All translations will be generated by LLMs.

Tip: If you are looking for a simpler way to translate string content, we recommend using the useGT() hook.


Advantages and disadvantages

There are a few advantages to using dictionaries:

  1. Centralized Storage: Dictionaries store all translatable content in a single file, making it easier to manage and update.
  2. Historical Precedent: The dictionary pattern is a common design pattern in the industry and is used by many other libraries.

At the same time, it has some disadvantages as well:

  1. Complexity: Dictionaries are more complex to set up and use than translating string content inline.
  2. Readability: Dictionaries are less readable than the inline translation because content is separated from the context where it is being used.
  3. Maintainability: Dictionaries are more difficult to maintain than inline translation because you need to manually update the dictionary file when content changes.

Dictionaries are an alternative design pattern to inline translation, but patterns are supported by our library and are not mutually exclusive. You can use a dictionary alongside inline translation with the <T> component and the useGT() hook.


Example

Specify your string content in a dictionary file (either .js or .json).

src/dictionary.json
{
  "greetings": {
    "hello": 'Hello, World!',
  },
} 

Then you reference it in your component by passing the key to the d() function.

src/MyComponent
import { GTProvider, useDict } from 'gt-react';
import dictionary from './dictionary.json';
 
export default function MyComponent() {
 
  const d = useDict(); 
 
  return (
    <GTProvider dictionary={dictionary}>
      <div>
        {d('greetings.hello')} // [!code highlight]
      </div>
    </GTProvider>
  );
}

Notes

  • Dictionaries are a way to translate content in General Translation.
  • The useDict() hook is used for translating strings with dictionary pattern.

Next steps

  • For more information check out the guides on dictionaries for React or Next.js

On this page