Skip to content
Clone
main
31 lines 1.2 KB
import { useCallback } from 'react'
import { DEFAULT_LOCALE, type Locale, useLocale } from './locale'
import { type MessageKey, type MessageParams, translate, translateCount } from './translate'
/**
* React-facing translation hooks. `useLocale` is the reactivity edge: any
* component that renders translated copy subscribes to it, so a language switch
* re-renders exactly the tree that depends on the locale (see `locale.ts`).
*
* `t`/`tc` resolve the dictionary at call time, which keeps them correct inside
* event handlers and memoised callbacks as well as during render.
*/
export type TranslateFn = (key: MessageKey, params?: MessageParams) => string
export type TranslateCountFn = (key: MessageKey, count: number, params?: MessageParams) => string
export interface I18n {
locale: Locale
fallback: Locale
t: TranslateFn
tc: TranslateCountFn
}
/** Hook form. Use it in every component that renders localized copy. */
export function useT(): I18n {
const locale = useLocale()
const t = useCallback<TranslateFn>((key, params) => translate(locale, key, params), [locale])
const tc = useCallback<TranslateCountFn>((key, count, params) => translateCount(locale, key, count, params), [locale])
return { locale, fallback: DEFAULT_LOCALE, t, tc }
}