Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(next-international) improve caching and calls #337

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ export function createI18nProviderClient<Locale extends BaseLocale>(
fallbackLocale?: Record<string, unknown>,
) {
function I18nProvider({ locale, importLocale, children }: I18nProviderProps) {
const clientLocale = (localesCache.get(locale) ?? use(importLocale).default) as Record<string, unknown>;

if (!localesCache.has(locale)) {
localesCache.set(locale, clientLocale);
}
const clientLocale = (localesCache.get(locale) ?? localesCache.set(locale, use(importLocale).default)) as Record<
string,
unknown
>;

const value = useMemo(
() => ({
Expand Down
20 changes: 15 additions & 5 deletions packages/next-international/src/common/create-t.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import type { ReactNode } from 'react';
import { cloneElement, isValidElement } from 'react';
import type { LocaleContext, LocaleMap, ReactParamsObject } from '../types';

let pluralKeysCache: Set<string> | undefined = undefined;

export function createT<Locale extends BaseLocale, Scope extends Scopes<Locale> | undefined>(
context: LocaleContext<Locale>,
scope: Scope | undefined,
Expand All @@ -23,12 +25,20 @@ export function createT<Locale extends BaseLocale, Scope extends Scopes<Locale>
? fallbackLocale
: Object.assign(fallbackLocale ?? {}, localeContent);

const pluralKeys = new Set(
Object.keys(content)
.filter(key => key.includes('#'))
.map(key => key.split('#', 1)[0]),
);
function getCachedPluralKeys() {
if (pluralKeysCache) {
return pluralKeysCache;
}

pluralKeysCache = new Set(
Object.keys(content)
.filter(key => key.includes('#'))
.map(key => key.split('#', 1)[0]),
);
return pluralKeysCache;
}

const pluralKeys = getCachedPluralKeys();
const pluralRules = new Intl.PluralRules(context.locale);

function getPluralKey(count: number) {
Expand Down