useTranslation
React hook to access translation function in Client Components
๐ฎInteractive Demo
Result:
Welcome
๐ก Try: Welcome, Getting Started, CLI Tools, etc.
Overview
useTranslation is a React hook that provides access to the translation function (t) and current language state. It can only be used in Client Components.
โSimple API with t() function
โAutomatic re-rendering on language change
โFallback to key if translation missing
โType-safe with TypeScript
API Reference
Return Value
t(key: string): stringTranslation function that returns the translated string for the given key.
const { t } = useTranslation();
const welcomeText = t("Welcome"); // "ํ์ํฉ๋๋ค" or "Welcome"currentLanguage: stringThe currently active language code.
const { currentLanguage } = useTranslation();
console.log(currentLanguage); // "ko" or "en"Usage Examples
Basic Usage
"use client";
import { useTranslation } from "i18nexus";
export default function Welcome() {
const { t } = useTranslation();
return (
<div>
<h1>{t("Welcome")}</h1>
<p>{t("This is a simple example")}</p>
</div>
);
}Dynamic Translation Keys
"use client";
import { useTranslation } from "i18nexus";
export default function StatusMessage({ status }) {
const { t } = useTranslation();
// Dynamically construct translation keys
const message = t(\`status.\${status}\`);
return <div>{message}</div>;
}
// Translations:
// "status.success": "์์
์ด ์ฑ๊ณตํ์ต๋๋ค"
// "status.error": "์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค"
// "status.pending": "์ฒ๋ฆฌ ์ค์
๋๋ค"Displaying Current Language
"use client";
import { useTranslation } from "i18nexus";
export default function LanguageDisplay() {
const { t, currentLanguage } = useTranslation();
return (
<div>
<p>{t("Current language")}: {currentLanguage}</p>
<p>{t("Welcome to our app")}</p>
</div>
);
}Real-World Example
"use client";
import { useTranslation } from "i18nexus";
interface Product {
id: string;
nameKey: string;
price: number;
}
export default function ProductCard({ product }: { product: Product }) {
const { t } = useTranslation();
return (
<div className="product-card">
<h2>{t(product.nameKey)}</h2>
<p className="price">
{t("Price")}: ${product.price}
</p>
<button>
{t("Add to cart")}
</button>
</div>
);
}Best Practices
โ Do: Use descriptive keys
Use clear, descriptive translation keys that indicate the content.
// Good
t("user.profile.edit.button")
t("error.network.timeout")
// Avoid
t("btn1")
t("msg")โ Do: Handle missing translations gracefully
i18nexus automatically returns the key if translation is missing, making debugging easier.
โDon't: Use in Server Components
useTranslation is a client-side hook. For Server Components, use createServerTranslation().
// โ Wrong - Server Component
export default async function Page() {
const { t } = useTranslation(); // Error!
}
// โ
Correct - Client Component
"use client";
export default function Page() {
const { t } = useTranslation(); // Works!
}โDon't: Construct keys with complex logic
Keep translation key logic simple and predictable.