Performance: Content translation management
This affects page load speed and interaction responsiveness by managing how translated content is loaded and rendered.
import { useRouter } from 'next/router'; import en from '../locales/en.json'; import fr from '../locales/fr.json'; const translations = { en, fr }; export default function Page() { const { locale } = useRouter(); const t = translations[locale] || translations.en; return <div>{t.welcome}</div>; }
import translations from '../locales/all-translations.json'; export default function Page() { const t = translations['en']; return <div>{t.welcome}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Import all translations at once | Minimal DOM changes | Multiple reflows due to delayed render | High paint cost due to large bundle | [X] Bad |
| Load only current locale translations | Minimal DOM changes | Single reflow on initial render | Low paint cost with smaller bundle | [OK] Good |
| Fetch translations on client after render | DOM updates after fetch | Reflow and layout shift on update | Medium paint cost with delayed content | [!] OK |
| Preload translations with static props | DOM ready with translations | Single reflow | Low paint cost, stable layout | [OK] Good |
useTranslations in a Next.js app?useTranslationsuseTranslations hook in a Next.js component?useTranslations hook comes from the next-intl package, which handles internationalization in Next.js.import { useTranslations } from 'next-intl'; is correct.useTranslations:
import { useTranslations } from 'next-intl';
export default function Greeting() {
const t = useTranslations('Greeting');
return <h1>{t('hello')}</h1>;
}
If the translation JSON for English is {"hello": "Hello!"} and for Spanish is {"hello": "¡Hola!"}, what will be rendered when the user language is Spanish?useTranslations works with keyst that looks up the key 'hello' in the 'Greeting' namespace for the current language.import { useTranslations } from 'next-intl';
export default function Page() {
const t = useTranslations('Home');
return <h2>{t('welcome')}</h2>;
}
But when running, you get an error: TypeError: t is not a function. What is the most likely cause?t is not a function, meaning useTranslations did not return a function.useTranslations with interpolation in Next.js?useTranslationsPass the test and this pattern moves unknown