From 88bfe23892bbb24b332d3dfe77f20dbba2e7b02c Mon Sep 17 00:00:00 2001 From: Tom Lienard Date: Sat, 10 Feb 2024 08:13:40 +0000 Subject: [PATCH] fix(next-international): locales switching on Pages Router (#352) --- .../src/common/create-use-i18n.ts | 16 ++-------------- .../src/common/create-use-scoped-i18n.ts | 17 ++--------------- 2 files changed, 4 insertions(+), 29 deletions(-) diff --git a/packages/next-international/src/common/create-use-i18n.ts b/packages/next-international/src/common/create-use-i18n.ts index c2a7233..dcfbca8 100644 --- a/packages/next-international/src/common/create-use-i18n.ts +++ b/packages/next-international/src/common/create-use-i18n.ts @@ -1,12 +1,10 @@ import type { Context } from 'react'; -import { useContext } from 'react'; +import { useContext, useMemo } from 'react'; import type { BaseLocale } from 'international-types'; import type { LocaleContext } from '../types'; import { createT } from './create-t'; export function createUsei18n(I18nClientContext: Context | null>) { - const localeCache = new Map>>(); - return function useI18n() { const context = useContext(I18nClientContext); @@ -14,16 +12,6 @@ export function createUsei18n(I18nClientContext: Cont throw new Error('`useI18n` must be used inside `I18nProvider`'); } - const cached = localeCache.get(context.locale); - - if (cached) { - return cached; - } - - const localeFn = createT(context, undefined); - - localeCache.set(context.locale, localeFn); - - return localeFn; + return useMemo(() => createT(context, undefined), [context]); }; } diff --git a/packages/next-international/src/common/create-use-scoped-i18n.ts b/packages/next-international/src/common/create-use-scoped-i18n.ts index e5c0132..3f143c6 100644 --- a/packages/next-international/src/common/create-use-scoped-i18n.ts +++ b/packages/next-international/src/common/create-use-scoped-i18n.ts @@ -1,5 +1,5 @@ import type { Context } from 'react'; -import { useContext } from 'react'; +import { useContext, useMemo } from 'react'; import type { BaseLocale, Scopes } from 'international-types'; import type { LocaleContext } from '../types'; import { createT } from '../common/create-t'; @@ -7,8 +7,6 @@ import { createT } from '../common/create-t'; export function createScopedUsei18n( I18nClientContext: Context | null>, ) { - const localeCache = new Map>>(); - return function useScopedI18n>(scope: Scope): ReturnType> { const context = useContext(I18nClientContext); @@ -16,17 +14,6 @@ export function createScopedUsei18n( throw new Error('`useI18n` must be used inside `I18nProvider`'); } - const cacheKey = `${context.locale}-${scope}`; - const cached = localeCache.get(cacheKey); - - if (cached) { - return cached; - } - - const localeFn = createT(context, scope); - - localeCache.set(cacheKey, localeFn); - - return localeFn; + return useMemo(() => createT(context, scope), [context, scope]); }; }