Skip to main content

Basic Usage

Learn how to use the LiveI18n React SDK for common translation scenarios in your application.

Prerequisites

Make sure you have wrapped your app with LiveI18nProvider as shown in the installation guide. All examples below assume your components are inside the provider.

The LiveText Component

The <LiveText> component is the core of the React SDK. It automatically translates any text content based on the user's language preferences.

Simple Translation

import { LiveText } from '@livei18n/react-sdk';

function WelcomeMessage() {
return (
<h1>
<LiveText>Welcome to our application!</LiveText>
</h1>
);
}

With Context and Tone

Provide context and tone for better translation quality:

function LoginForm() {
return (
<div>
<LiveText
context="login form"
tone="friendly"
>
Please sign in to continue
</LiveText>
</div>
);
}

With Language Override

Force translation to a specific language:

function MultiLanguageGreeting() {
return (
<div>
<LiveText language="es-ES">Welcome to our app!</LiveText>
<LiveText language="fr-FR">Welcome to our app!</LiveText>
<LiveText language="zh-CN">Welcome to our app!</LiveText>
</div>
);
}

With Dynamic Content

Handle dynamic variables within translated text:

function NotificationBadge({ count, userName }) {
return (
<div>
<LiveText context="personalized greeting">
Welcome back, {userName}!
</LiveText>
<LiveText context="notification count">
You have {count} {count === 1 ? 'notification' : 'notifications'}
</LiveText>
</div>
);
}

The useLiveText Hook

The useLiveText hook provides a programmatic way to translate text and returns a string value. This is perfect for scenarios where you need translated text in JavaScript logic rather than directly in JSX.

Basic Usage

import { useLiveText } from '@livei18n/react-sdk';

function UserProfile({ user }) {
const greeting = useLiveText("Hello");
const welcomeMessage = useLiveText("Welcome back!");

return (
<div>
<h1>{greeting}, {user.name}!</h1>
<p>{welcomeMessage}</p>
</div>
);
}

With Context and Tone

function StatusIndicator({ status }) {
const statusText = useLiveText("Processing your request", {
context: "loading indicator",
tone: "reassuring"
});

const buttonLabel = useLiveText("Cancel", {
context: "action button",
tone: "neutral"
});

return (
<div>
<p>{statusText}</p>
<button>{buttonLabel}</button>
</div>
);
}

Dynamic Content Translation

function NotificationBadge({ count }) {
const notificationText = useLiveText(
count === 1 ? "You have 1 notification" : `You have ${count} notifications`,
{ context: "notification badge" }
);

return <span className="badge">{notificationText}</span>;
}

Language-Specific Translation

function MultiLanguageAlert() {
const englishAlert = useLiveText("Important update available", {
language: "en-US",
context: "system alert"
});

const spanishAlert = useLiveText("Important update available", {
language: "es-ES",
context: "system alert"
});

return (
<div>
<p>English: {englishAlert}</p>
<p>Spanish: {spanishAlert}</p>
</div>
);
}

When to Use useLiveText vs LiveText

Use useLiveText when you need a translated string and can't use a component (JavaScript logic, state values, alerts, etc.)

Use <LiveText> when you can use a component directly in your JSX.

function MixedApproach({ user, notifications }) {
const greeting = useLiveText(`Welcome, ${user.name}!`, {
context: "personalized greeting"
});

return (
<div>
<h1>{greeting}</h1>
<p>
<LiveText context="notification count">
You have {notifications.length} unread messages
</LiveText>
</p>
</div>
);
}

Automatic Language Updates

The useLiveText hook automatically responds to default language changes, just like the <LiveText> component:

function LanguageAwareComponent() {
const { updateDefaultLanguage } = useLiveI18n();
const buttonText = useLiveText("Switch Language");

const handleLanguageChange = () => {
updateDefaultLanguage("es-ES");
// buttonText will automatically update to Spanish
};

return (
<button onClick={handleLanguageChange}>
{buttonText}
</button>
);
}

Language Detection

Automatic Detection

By default, LiveI18n uses the SDK's default language, or auto-detects from browser settings if none is set:

// Translates with no language override
<LiveText>Hello, world!</LiveText>

Explicit Language

Override the automatic detection with a specific language:

// Force Spanish translation
<LiveText language="es-ES">Hello, world!</LiveText>

// Use language codes or natural language
<LiveText language="spanish">Hello, world!</LiveText>
<LiveText language="français">Hello, world!</LiveText>

Common Patterns

function Navigation() {
return (
<nav>
<ul>
<li><LiveText context="navigation">Home</LiveText></li>
<li><LiveText context="navigation">About</LiveText></li>
<li><LiveText context="navigation">Contact</LiveText></li>
<li><LiveText context="navigation">Products</LiveText></li>
</ul>
</nav>
);
}

Form Labels

function ContactForm() {
return (
<form>
<label>
<LiveText context="form label">Full Name</LiveText>
<input type="text" />
</label>

<label>
<LiveText context="form label">Email Address</LiveText>
<input type="email" />
</label>

<label>
<LiveText context="form label">Message</LiveText>
<textarea />
</label>

<button type="submit">
<LiveText context="form button" tone="action">
Send Message
</LiveText>
</button>
</form>
);
}

Error Messages

function ErrorMessage({ error }) {
if (!error) return null;

return (
<div className="error">
<LiveText context="error message" tone="apologetic">
{error}
</LiveText>
</div>
);
}

Success Messages

function SuccessMessage() {
return (
<div className="success">
<LiveText context="success message" tone="celebratory">
Your account has been created successfully!
</LiveText>
</div>
);
}

Best Practices

1. Use Descriptive Context

// ✅ Good - provides clear context
<LiveText context="shopping cart button">Add to Cart</LiveText>

// ❌ Avoid - too generic
<LiveText context="button">Add to Cart</LiveText>

2. Choose Appropriate Tone

// ✅ Match tone to content
<LiveText tone="professional">Terms of Service</LiveText>
<LiveText tone="friendly">Welcome!</LiveText>
<LiveText tone="urgent">Action Required</LiveText>

3. Keep Text Semantic

// ✅ Semantic and translatable
<LiveText>Learn More</LiveText>

// ❌ Avoid technical jargon that doesn't translate well
<LiveText>onClick Handler</LiveText>

4. Handle Edge Cases

function ProductPrice({ price, currency }) {
// Don't translate currency symbols or numbers
return (
<div>
<LiveText context="product pricing">Price:</LiveText>
{' '}
<span>{price} {currency}</span>
</div>
);
}

Performance Considerations

Caching Behavior

The SDK automatically caches translations:

// These will be cached and reused
<LiveText>Home</LiveText> // Cache hit after first load
<LiveText>Home</LiveText> // Instant from cache

Avoiding Cache Pollution

// ✅ Good - stable cache keys
<LiveText context="greeting">Hello</LiveText>

// ⚠️ Be careful - creates many cache entries
<LiveText>Hello {Math.random()}</LiveText> // Don't do this

Memory Management

The SDK uses LRU (Least Recently Used) cache eviction:

  • 500 entries by default (customizable)
  • 1-hour TTL by default (customizable)
  • Automatic cleanup of expired entries

Error Handling

Graceful Fallbacks

The SDK automatically falls back to original text if translation fails:

// If translation fails, shows "Hello, world!"
<LiveText>Hello, world!</LiveText>

Network Errors

Translations continue working during network issues thanks to caching:

// Works offline if previously cached
<LiveText>Welcome back!</LiveText>

Testing Your Implementation

Getting Supported Languages

The SDK provides a method to fetch the list of languages supported by LiveI18n, which you can use to build language selectors or display available languages to users.

Using the Hook

import { useLiveI18n } from '@livei18n/react-sdk';

function LanguageSelector() {
const { getSupportedLanguages } = useLiveI18n();
const [languages, setLanguages] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchLanguages = async () => {
try {
// Get top 20 most popular languages
const response = await getSupportedLanguages();
setLanguages(response.languages);
} catch (error) {
console.error('Failed to fetch languages:', error);
} finally {
setLoading(false);
}
};

fetchLanguages();
}, []);

if (loading) return <div>Loading languages...</div>;

return (
<select>
{languages.map(lang => (
<option key={lang.locale} value={lang.locale}>
{lang.flag} {lang.name}
</option>
))}
</select>
);
}

Getting All Languages

By default, getSupportedLanguages() returns the top 20 most popular languages. To get all supported languages:

// Get all supported languages (not just top 20)
const response = await getSupportedLanguages(true);
console.log(`Total languages: ${response.total}`);

Response Format

The getSupportedLanguages() method returns:

interface SupportedLanguagesResponse {
languages: SupportedLanguage[];
total: number;
}

interface SupportedLanguage {
name: string; // "Spanish (Spain)"
locale: string; // "es-ES"
flag: string; // "🇪🇸"
}

Caching Behavior

Language lists are cached for 1 hour to improve performance:

// First call - fetches from API
const languages1 = await getSupportedLanguages();

// Second call within 1 hour - returns from cache
const languages2 = await getSupportedLanguages();

The cache maintains separate entries for top 20 vs all languages.

Manual Testing

  1. Change your browser language settings
  2. Reload your application
  3. Verify translations appear correctly

Using the Demo

Test your text with the interactive demo:

  1. Enter your API keys
  2. Try your exact text strings
  3. Test different languages and contexts

Browser Dev Tools

Monitor translation behavior:

  1. Open Network tab
  2. Look for API calls to api.livei18n.com
  3. Check for successful responses and caching

Common Use Cases

E-commerce

function ProductCard({ product }) {
return (
<div className="product-card">
<h3>{product.name}</h3>
<p>
<LiveText context="product price">Price:</LiveText>
{' '}${product.price}
</p>
<button>
<LiveText context="shopping action">Add to Cart</LiveText>
</button>
</div>
);
}

Dashboard

function Dashboard({ stats }) {
return (
<div className="dashboard">
<h1>
<LiveText context="dashboard title">Analytics Dashboard</LiveText>
</h1>

<div className="stats-grid">
<div className="stat">
<h2>{stats.users}</h2>
<p>
<LiveText context="dashboard metric">Active Users</LiveText>
</p>
</div>
<div className="stat">
<h2>{stats.revenue}</h2>
<p>
<LiveText context="dashboard metric">Total Revenue</LiveText>
</p>
</div>
</div>
</div>
);
}

Next Steps

Now that you understand basic usage:

Troubleshooting

Translations Not Appearing

  1. Check browser console for errors
  2. Verify SDK initialization
  3. Test API keys with the demo
  4. Check network requests in dev tools

Slow Performance

  1. Monitor cache hit rates
  2. Avoid translating dynamic content
  3. Use consistent context and tone
  4. Check for excessive re-renders

Need help? Contact our support team or check the troubleshooting guide.