How to implement internationalization in React components using the useTranslation hook.
The useTranslation hook provides a consistent API for handling translations, formatting dynamic content, and managing locale-sensitive data across the application.
The formatMessage function handles all text translations and supports multiple signatures. The function now requires a translation key as the first parameter, followed by the default message.
The formatMessage function supports ICU Message syntax for pluralization:
If you need more complex pluralization (e.g., zero, two), you can use:
or
Translation keys should follow a hierarchical naming convention:
Examples:
Key Structure Recommendations:
The formatNumber function formats numbers according to locale:
The context parameter is crucial for providing translators with additional information about where and how the text is used. Combined with descriptive translation keys, this provides comprehensive context for translators:
formatMessage callformatMessageformatNumber for all numeric valuesformatNumberuseTranslation hook with working APIHook used outside provider
Solution: Ensure your component tree is wrapped with TranslationProvider
Missing context parameter While not required, missing context makes translation difficult. Always provide meaningful context. The shorter the string the more important context becomes.
Numbers not formatting Ensure you're using formatNumber instead of manual formatting or .toString()
The current implementation logs all localization calls to the console in development mode:
On this page