useTranslation
- React Native course
- Expert
- Lesson 34/47
- 5 min
Learn the useTranslation hook.
The useTranslation hook
useTranslation is a hook from react-i18next. It is the cleanest way to reach the t function inside a component. Instead of passing t through props each component calls its own translation.
Usage: const { t } = useTranslation();. Then you write <Text>{t('hello')}</Text>. The hook returns t for the active language; when the language changes the component re-renders automatically. This removes prop drilling. useTranslation also returns the i18n object; it is used for language switching.
Practice Use useTranslation
Write a Greeting component. Call useTranslation() and take t. Return <Text>{t('hello')}</Text>.
Starter code
import React from 'react';
import { Text } from 'react-native';
import { useTranslation } from 'react-i18next';
function Greeting() {
// useTranslation call and Text return
return <Text>Static</Text>;
}Sample solution
import React from 'react';
import { Text } from 'react-native';
import { useTranslation } from 'react-i18next';
function Greeting() {
const { t } = useTranslation();
return <Text>{t('hello')}</Text>;
}The t function parameters
The t function does not only take a key; it also takes parameters. For example t('welcome', { name: 'Alex' }) fills the {{ name }} slot in the translation. Translation: "welcome": "Welcome, {{name}}".
Result: "Welcome, Alex". This is known as interpolation. Pluralization is also supported: t('item', { count: 3 }). The translation file defines "item_one": "one item", "item_other": "{{count}} items". This keeps dynamic strings clean; no string concatenation.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useTranslation return?
const { t, i18n } = useTranslation();- An empty object
- Only i18n
- Only t
- t and i18n Correct answer
Explanation: useTranslation returns both t and i18n.
2 useTranslation call
const { ____ } = useTranslation();
const { t } = useTranslation();
Explanation: t is the translate function.
3 Match each piece to its role
| Term | Meaning |
|---|---|
useTranslation |
Hook |
t |
Returns translation |
i18n |
Manages language |
react-i18next |
Library |