commits

v0.48.0: Context API로 가벼운 다국어 지원 구현하기

R
이더
2026.03.07 11:09 · 1 min read

🤖 2306 in / 875 out / 3181 total tokens

Context API 기반으로 경량 i18n 시스템을 직접 구현했다. react-i18next 같은 라이브러리 없이 번들 크기를 아끼면서도 충분한 기능을 갖췄다. LocaleContext와 useLocale 훅으로 현재 언어 상태를 관리하고, localStorage에 사용자 선택을 저장한다. 브라우저 언어 자동 감지로 첫 방문 시 적절한 언어를 보여준다.

번역 파일은 ko.json, en.json으로 분리했고, 파라미터 인터폴레이션도 지원한다. LanguageSelector 컴포넌트는 Globe 아이콘과 함께 모바일/데스크톱 양쪽에 배치했다. 8개 테스트를 추가해 총 720개 테스트가 통과했다.

// LocaleContext 핵심 구조
const LocaleContext = createContext<LocaleContextType | null>(null);
 
export function LocaleProvider({ children, defaultLocale = 'ko' }) {
  const [locale, setLocaleState] = useState<Locale>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('locale');
      if (stored && isValidLocale(stored)) return stored;
      return getBrowserLocale();
    }
    return defaultLocale;
  });
 
  const setLocale = useCallback((newLocale: Locale) => {
    setLocaleState(newLocale);
    localStorage.setItem('locale', newLocale);
  }, []);
 
  const t = useCallback((key: string, params?: Record<string, string>) => {
    return translate(key, locale, params);
  }, [locale]);
 
  return (
    <LocaleContext.Provider value={{ locale, setLocale, t }}>
      {children}
    </LocaleContext.Provider>
  );
}

직접 구현하니 번들 크기 걱정 없고, 필요한 만큼만 딱 챙길 수 있어 만족스럽다.

← 이전 글
v0.47.0: ESLint 0 달성, React Hook 규칙 준수
다음 글 →
LocaleContext ESLint 에러 해결과 useState lazy initialization