Client Components
This guide explains how to use the internationalization package with React Client Components in your Next.js application.Overview
Client Components run in the browser and can include interactive features. To use translations in Client Components, you need to:- Wrap your Client Components with the
TranslationProvider
in a Server Component - Use the
useTranslation
hook in your Client Components to access translations
Setting Up the Translation Provider
In a Server Component that renders your Client Component, wrap the Client Component with theTranslationProvider
:
TranslationProvider
component:
- Takes the current locale and dictionary as props
- Makes translations available to all Client Components within its subtree
- Uses
next-intl
under the hood to provide translations
Using the useTranslation Hook
In your Client Components, import and use theuseTranslation
hook to access translations:
useTranslation
hook:
- Takes a namespace parameter that specifies which part of the translation object to use
- Returns a
t
function that you can use to access translations within that namespace - Automatically updates when the locale changes
Namespace Parameter
The namespace parameter in theuseTranslation
hook helps you access a specific section of your translations:
Dynamic Values and Formatting
You can include dynamic values in your translations:Pluralization
You can handle pluralization in your translations:Creating a Language Switcher
You can create a language switcher component to allow users to change the language:Best Practices
Keep Client Components Small
Keep Client Components Small
Split large Client Components into smaller ones and use the appropriate namespace for each component to keep translations organized.
Use TypeScript for Type Safety
Use TypeScript for Type Safety
Define types for your translations to get better IDE support:
Handle Missing Translations
Handle Missing Translations
Always provide fallbacks for translations that might be missing: