next-localize
v1.0.1
Published
A React hook for internationalization with dynamic locale loading and cookie persistence
Maintainers
Readme
next-localize
A React hook for internationalization with dynamic locale loading and cookie persistence. Perfect for Next.js applications.
Features
- 🌍 Dynamic locale loading - add your own translation files
- 🍪 Cookie persistence - language preference saved automatically
- 🔄 Automatic fallback to English if no language is stored
- 📦 Easy setup with optional locales folder creation
- 🎯 TypeScript support
- ⚡ Built with Zustand for optimal performance
Installation
npm install next-localizeDuring installation, you'll be prompted to create a locales folder with example files. You can skip this if you already have your locale files.
Setup
1. Create Locale Files
Create a locales folder in your project root and add your translation files:
locales/
en.json
fr.json
jp.jsonExample en.json:
{
"welcome": "Hello, World! Welcome to next-localize"
}2. Initialize Translations
In your app (e.g., app/layout.tsx or _app.tsx):
import { initTranslations } from 'next-localize';
import en from './locales/en.json';
import fr from './locales/fr.json';
import jp from './locales/jp.json';
// Recommended: Initialize all translations at once
initTranslations({
en,
fr,
jp,
});
// Alternative: Add locales individually
import { useLangStore } from 'next-localize';
useLangStore.getState().addLocale('en', en);
useLangStore.getState().addLocale('fr', fr);
useLangStore.getState().addLocale('jp', jp);3. Use the Hook
import { useTranslate } from 'next-localize';
function MyComponent() {
const Translate = useTranslate();
return (
<div>
<h1>
{Translate(
"Hello, World! Welcome to next-localize",
"welcome"
)}
</h1>
</div>
);
}API
useTranslate()
Returns a translation function that takes:
defaultText: Fallback text if translation is not foundkey: Dot-notation path to the translation (e.g.,"Auth.SignupForm.createAnAccount")
useLangStore
Zustand store for managing language state:
import { useLangStore } from 'next-localize';
// Get current language
const lang = useLangStore((s) => s.lang);
// Change language (automatically saved to cookies)
useLangStore.getState().setLang('fr');
// Add a new locale
useLangStore.getState().addLocale('es', spanishTranslations);
// Set all translations
useLangStore.getState().setTranslations({
en: englishTranslations,
fr: frenchTranslations,
});Cookie Management
The package automatically:
- Saves the selected language to cookies when changed
- Loads the language from cookies on page load
- Falls back to English if no cookie is found
Cookie name: use-translate-lang
Next.js Integration
The hook automatically detects the lang parameter from Next.js routes:
// If your route is /[lang]/page, it will use that lang
// Otherwise, it falls back to the cookie or 'en'License
MIT
