mediumExtra#95

i18n with expo-localization

Prompt

Use expo-localization to detect the device language with the modern getLocales() API. Create a simple i18n object that returns translated strings for English and Spanish, falling back to English for unsupported languages.

Solution

export default function Greeting() {
  const languageCode = Localization.getLocales()[0]?.languageCode ?? 'en'
  const t = translations[languageCode] ?? translations.en
  return (
    <View>
      <Text>{t.greeting}</Text>
      <Text>{t.farewell}</Text>
    </View>
  )
}
Mentor's take

i18n at this size is two decisions: where the locale comes from, and what happens when you don't support it. Localization.getLocales() returns the user's preference list, most-preferred first, already parsed — languageCode gives you 'es' from es-MX, so every regional variant shares one dictionary. The older Localization.locale string (and the split('-')[0] parsing it forced) is the deprecated pattern this API replaced; using it in an interview dates your Expo knowledge.

The fallback chain is the production-critical line. translations[languageCode] for a French device returns undefined, and without ?? translations.en the next property access crashes. Falling back to the default language fails soft: wrong language beats a dead screen, every time.

Trade-offs to defend: a plain object is honest for two locales and a take-home. The moment you need interpolation, pluralization, or lazy-loaded dictionaries, reach for i18n-js or react-i18next — plural rules alone justify it, since some languages have up to six plural categories and Intl.PluralRules exists precisely because count === 1 ? 'item' : 'items' is wrong outside English.

Red flag: caching the locale in a module-level constant. The user can change device language while your app is backgrounded; resolve it per render (or subscribe) or the app ignores the change until a full restart.

Say it: "I resolve languageCode from getLocales(), fall back to the default language so unsupported locales degrade instead of crash, and reach for a real i18n library the moment pluralization or interpolation appears."