React Integration Guide

Integrate SiteLocaleAI into your React or Next.js application with a custom hook and language switcher component.

1

Install and Start the SDK

Make sure your SDK backend is running.

Before integrating with React, you need the SiteLocaleAI SDK running. If you have not set it up yet, follow the Getting Started tutorial first.

Verify the SDK is accessible from your React app by hitting the health endpoint:

You should get a JSON response confirming the SDK is running.

Terminal

# Check that the SDK is running
curl http://localhost:4000/health

# Expected response:
# {"ok":true}

src/hooks/useSiteLocale.ts

// src/hooks/useSiteLocale.ts
import { useState, useEffect, useCallback, useRef } from "react";

interface UseSiteLocaleOptions {
  sdkUrl: string;
  defaultLocale?: string;
}

interface Translations {
  [key: string]: string;
}

export function useSiteLocale({
  sdkUrl,
  defaultLocale = "en",
}: UseSiteLocaleOptions) {
  const [locale, setLocale] = useState(defaultLocale);
  const [loading, setLoading] = useState(false);
  const cache = useRef<Record<string, Translations>>({});

  useEffect(() => {
    if (locale === defaultLocale) return;
    if (cache.current[locale]) return;

    setLoading(true);
    fetch(`${sdkUrl}/translate/bundle?locale=${locale}`)
      .then((res) => res.json())
      .then((data) => {
        cache.current[locale] = data.translations;
      })
      .finally(() => setLoading(false));
  }, [locale, sdkUrl, defaultLocale]);

  const t = useCallback(
    (key: string, fallback?: string) => {
      if (locale === defaultLocale) return fallback ?? key;
      return cache.current[locale]?.[key] ?? fallback ?? key;
    },
    [locale, defaultLocale]
  );

  return { locale, setLocale, t, loading };
}
2

Create the useSiteLocale Hook

A custom React hook that manages translations.

Create a new file for the translation hook. This hook fetches translations from your SDK and provides them to your components:

The hook caches translations in a ref to avoid unnecessary re-renders and re-fetches only when the locale changes.

src/hooks/useSiteLocale.ts

// src/hooks/useSiteLocale.ts
import { useState, useEffect, useCallback, useRef } from "react";

export function useSiteLocale({ sdkUrl, defaultLocale = "en" }) {
  const [locale, setLocale] = useState(defaultLocale);
  const [loading, setLoading] = useState(false);
  const cache = useRef({});

  useEffect(() => {
    if (locale === defaultLocale || cache.current[locale]) return;
    setLoading(true);
    fetch(`${sdkUrl}/translate/bundle?locale=${locale}`)
      .then((res) => res.json())
      .then((data) => { cache.current[locale] = data.translations; })
      .finally(() => setLoading(false));
  }, [locale, sdkUrl, defaultLocale]);

  const t = useCallback(
    (key, fallback) =>
      locale === defaultLocale
        ? fallback ?? key
        : cache.current[locale]?.[key] ?? fallback ?? key,
    [locale, defaultLocale]
  );

  return { locale, setLocale, t, loading };
}
3

Use Translations in Components

Replace hardcoded strings with the t() function.

Wrap your app with a locale context provider and use the hook in any component that needs translations:

The t() function returns the translated string for the current locale. If a translation is not yet loaded, it falls back to the original text.

src/providers/LocaleProvider.tsx

// src/providers/LocaleProvider.tsx
import { createContext, useContext, ReactNode } from "react";
import { useSiteLocale } from "../hooks/useSiteLocale";

const LocaleContext = createContext<ReturnType<
  typeof useSiteLocale
> | null>(null);

export function LocaleProvider({ children }: { children: ReactNode }) {
  const locale = useSiteLocale({
    sdkUrl: "https://your-sdk.example.com",
  });

  return (
    <LocaleContext.Provider value={locale}>
      {children}
    </LocaleContext.Provider>
  );
}

export const useLocale = () => {
  const ctx = useContext(LocaleContext);
  if (!ctx) throw new Error("Wrap your app in <LocaleProvider>");
  return ctx;
};

src/components/PricingCard.tsx

// src/components/PricingCard.tsx
import { useLocale } from "../providers/LocaleProvider";

export function PricingCard() {
  const { t } = useLocale();

  return (
    <div className="pricing-card">
      <h2>{t("pricing.title", "Growth Plan")}</h2>
      <p>{t("pricing.desc", "For growing businesses")}</p>
      <span data-price="99" data-currency="USD">
        $99/month
      </span>
      <button>{t("pricing.cta", "Start free trial")}</button>
    </div>
  );
}

src/components/LanguageSwitcher.tsx

// src/components/LanguageSwitcher.tsx
import { useLocale } from "../providers/LocaleProvider";

const LANGUAGES = [
  { code: "en", label: "English" },
  { code: "de", label: "Deutsch" },
  { code: "fr", label: "Français" },
  { code: "es", label: "Español" },
  { code: "ja", label: "日本語" },
];

export function LanguageSwitcher() {
  const { locale, setLocale, loading } = useLocale();

  return (
    <select
      value={locale}
      onChange={(e) => setLocale(e.target.value)}
      disabled={loading}
    >
      {LANGUAGES.map((lang) => (
        <option key={lang.code} value={lang.code}>
          {lang.label}
        </option>
      ))}
    </select>
  );
}
4

Add a Language Switcher

Let users choose their preferred language.

Create a dropdown component that switches the active locale:

Place the LanguageSwitcher component in your header or navigation bar. When a user selects a language, the hook re-fetches translations and your UI updates automatically.

src/components/LanguageSwitcher.tsx

// src/components/LanguageSwitcher.tsx
import { useLocale } from "../providers/LocaleProvider";

export function LanguageSwitcher() {
  const { locale, setLocale, loading } = useLocale();
  const langs = [
    { code: "en", label: "English" },
    { code: "de", label: "Deutsch" },
    { code: "fr", label: "Français" },
  ];

  return (
    <select value={locale}
      onChange={(e) => setLocale(e.target.value)}
      disabled={loading}>
      {langs.map((l) => (
        <option key={l.code} value={l.code}>{l.label}</option>
      ))}
    </select>
  );
}

Your React app is now multilingual!

Explore price localization and SEO pre-rendering to take your international React app to the next level.