Localization
Usage
How to use the useTranslation hook in your React components
Usage
The useTranslation hook provides internationalization functionality with support for multiple languages including English, Spanish, French, Japanese, Korean, and Portuguese.
Basic Example
import { useTranslation } from "@/lib/i18n";
function MyComponent() {
const userName = 'User';
const notificationsCount = 2;
const { t, currentLanguage, changeLanguage } = useTranslation();
return (
<div>
<h1>{t('Welcome, {{userName}}', { userName })}</h1>
<p>Current language: {currentLanguage}</p>
<button onClick={() => changeLanguage('es')}>Switch to Spanish</button>
<p>
{t('You have a new notification', {
count: notificationsCount,
plural: 'You have {{count}} new notifications',
})}
</p>
</div>
);
}Available Methods
t(key: string): Translate a key to the current language- See the full list of parameters here
pluralis a wrapper fordefaultValue_other. This value is used for English localization
changeLanguage(language: string): Change the current languagecurrentLanguage: Get the current language codei18n: Access the i18n instance for advanced usage
Supported Languages
en- English (default)es- Spanishfr- Frenchja- Japaneseko- Koreanpt- Portuguese (Brazil)
Language Persistence
The hook automatically saves the selected language to localStorage using the key app_language and restores it on subsequent visits.
Adding New Translations
To add new translation keys, update the JSON files in the locales directory:
// locales/es.json
{
"Welcome": "Bienvenido",
}Advanced Usage
import { useTranslation, saveLanguage, getSavedLanguage } from "@/lib/i18n";
function LanguageSelector() {
const { t, changeLanguage, currentLanguage } = useTranslation();
const handleLanguageChange = async (lang: string) => {
await changeLanguage(lang);
saveLanguage(lang);
};
return (
<select
value={currentLanguage}
onChange={(e) => handleLanguageChange(e.target.value)}
>
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
<option value="ja">日本語</option>
<option value="ko">한국어</option>
<option value="pt">Português</option>
</select>
);
}