CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-i18next

React integration for i18next internationalization framework with hooks, components, and SSR support

Pending
Overview
Eval results
Files

hooks.mddocs/

React Hooks

React i18next provides modern React hooks for accessing translation functionality in functional components with automatic re-rendering and type safety.

Capabilities

useTranslation Hook

The primary hook for accessing translation functions and i18next instance in React components. Automatically re-renders components when language changes or translations are updated.

/**
 * React hook providing translation function and i18next instance
 * @param ns - Namespace(s) to load and use for translations
 * @param options - Configuration options for the hook
 * @returns Array/object with [t, i18n, ready] plus named properties
 */
function useTranslation<
  const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,
  const KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined
>(
  ns?: Ns,
  options?: UseTranslationOptions<KPrefix>
): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;

interface UseTranslationOptions<KPrefix> {
  /** Custom i18next instance (defaults to context or global instance) */
  i18n?: i18n;
  /** Enable React Suspense mode for async loading */
  useSuspense?: boolean;
  /** Prefix automatically added to all translation keys */
  keyPrefix?: KPrefix;
  /** Events to bind for re-rendering (default: 'languageChanged') */
  bindI18n?: string | false;
  /** Namespace resolution mode */
  nsMode?: 'fallback' | 'default';
  /** Target language override */
  lng?: string;
}

type UseTranslationResponse<Ns extends Namespace, KPrefix> = [
  t: TFunction<Ns, KPrefix>,
  i18n: i18n,
  ready: boolean
] & {
  /** Translation function with type-safe keys */
  t: TFunction<Ns, KPrefix>;
  /** i18next instance for language changes and configuration */
  i18n: i18n;
  /** Indicates if translations are loaded and ready */
  ready: boolean;
};

Usage Examples:

import { useTranslation } from "react-i18next";

// Basic usage
function Welcome() {
  const { t } = useTranslation();
  return <h1>{t('welcome')}</h1>;
}

// With namespace
function UserProfile() {
  const { t } = useTranslation('user');
  return <div>{t('profile.title')}</div>;
}

// With key prefix
function Settings() {
  const { t } = useTranslation('common', { keyPrefix: 'settings' });
  return <button>{t('save')}</button>; // Resolves to 'common:settings.save'
}

// Multiple namespaces with fallback
function Dashboard() {
  const { t, i18n, ready } = useTranslation(['dashboard', 'common']);
  
  if (!ready) return <div>Loading...</div>;
  
  return (
    <div>
      <h1>{t('title')}</h1>
      <button onClick={() => i18n.changeLanguage('de')}>
        {t('common:switchLanguage')}
      </button>
    </div>
  );
}

// With interpolation and pluralization
function ItemCounter({ count }: { count: number }) {
  const { t } = useTranslation();
  return <p>{t('itemCount', { count })}</p>; // Handles plural forms
}

// Custom i18next instance
function IsolatedComponent({ i18nInstance }: { i18nInstance: i18n }) {
  const { t } = useTranslation('isolated', { i18n: i18nInstance });
  return <span>{t('message')}</span>;
}

useSSR Hook

Hook for server-side rendering support that initializes i18next with pre-loaded translations and language settings.

/**
 * Initializes i18next instance with SSR data for hydration
 * @param initialI18nStore - Pre-loaded translation resources from server
 * @param initialLanguage - Initial language from server
 * @param props - Additional options including custom i18next instance
 */
function useSSR(
  initialI18nStore: Resource,
  initialLanguage: string,
  props?: { i18n?: i18n }
): void;

Usage Examples:

import { useSSR, useTranslation } from "react-i18next";

// Next.js page component
function HomePage({ initialI18nStore, initialLanguage }) {
  useSSR(initialI18nStore, initialLanguage);
  const { t } = useTranslation();
  
  return <h1>{t('welcome')}</h1>;
}

// With custom i18next instance
function CustomSSRComponent({ ssrData, customI18n }) {
  useSSR(ssrData.store, ssrData.language, { i18n: customI18n });
  const { t } = useTranslation();
  
  return <div>{t('content')}</div>;
}

// In Next.js getServerSideProps or getStaticProps
export async function getServerSideProps(context) {
  const { initialI18nStore, initialLanguage } = getInitialProps();
  
  return {
    props: {
      initialI18nStore,
      initialLanguage
    }
  };
}

Type Definitions

// Namespace resolution types
type FallbackNs<Ns> = Ns extends undefined
  ? TypeOptions['defaultNS']
  : Ns extends Namespace
    ? Ns
    : TypeOptions['defaultNS'];

// Conditional hook signature based on i18next selector support
type UseTranslationHook = TypeOptions['enableSelector'] extends true | 'optimize'
  ? UseTranslationSelector
  : UseTranslationLegacy;

interface UseTranslationLegacy {
  <
    const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,
    const KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined
  >(
    ns?: Ns,
    options?: UseTranslationOptions<KPrefix>
  ): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;
}

interface UseTranslationSelector {
  <
    const Ns extends FlatNamespace | $Tuple<FlatNamespace> | undefined = undefined,
    const KPrefix = undefined
  >(
    ns?: Ns,
    options?: UseTranslationOptions<KPrefix>
  ): UseTranslationResponse<FallbackNs<Ns>, KPrefix>;
}

// SSR resource type from i18next
interface Resource {
  [language: string]: {
    [namespace: string]: any;
  };
}

Hook Behavior

Re-rendering Triggers

The useTranslation hook automatically triggers component re-renders when:

  • Language changes via i18n.changeLanguage()
  • Translations are added or updated via i18n.addResource() or i18n.addResourceBundle()
  • Namespace loading completes
  • Custom events specified in bindI18n option

Suspense Support

When useSuspense: true (default), the hook integrates with React Suspense:

  • Component suspends during translation loading
  • Resumes rendering when resources are ready
  • Set useSuspense: false for manual loading state handling

Error Handling

The hook handles common error scenarios:

  • Missing i18next instance: Returns fallback translation function
  • Missing translations: Falls back to key or default values
  • Network errors: Continues with cached or fallback translations
  • Invalid namespaces: Logs warnings and continues with available namespaces

Install with Tessl CLI

npx tessl i tessl/npm-react-i18next

docs

components.md

hocs.md

hooks.md

icu-macro.md

index.md

ssr.md

tile.json