Skip to content

Commit

Permalink
add useMemo cache too, in case we're juggling with many intlConfigs
Browse files Browse the repository at this point in the history
  • Loading branch information
zbigg committed Jul 29, 2024
1 parent 9c92cdd commit 31ab222
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/react-ui/src/hooks/useImperativeIntl.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createIntl, createIntlCache } from 'react-intl';
import { messages } from '../localization';
import { useMemo } from 'react';
import {
flattenMessages,
findMatchingMessagesLocale,
Expand All @@ -11,12 +12,12 @@ const cache = createIntlCache();
let lastIntlConfig;
let cachedC4rIntl;

export default function useImperativeIntl(intlConfig) {
const getGloballyCachedIntl = (intlConfig) => {
if (!cachedC4rIntl || lastIntlConfig !== intlConfig) {
// this is very naive cache that bases on fact that Intl instance is actually same for most of time
// This is very simple cache exploits fact that Intl instance is actually same for most of time
// so we can reuse those maps across several instances of same components
// note, useMemo can't do that globally and flattenMessages over _app_ and c4r is quite costly and would
// be paid for evey c4r component mounted
// be paid for every c4r component mounted.
const locale = intlConfig?.locale || DEFAULT_LOCALE;
const messagesLocale = findMatchingMessagesLocale(locale, messages);
const intMessages = {
Expand All @@ -35,4 +36,9 @@ export default function useImperativeIntl(intlConfig) {
lastIntlConfig = intlConfig;
}
return cachedC4rIntl;
};

export default function useImperativeIntl(intlConfig) {
// second level cache, in components is just to avoid re-creating the Intl instance if user is rendering many languages in one app
return useMemo(() => getGloballyCachedIntl(intlConfig), [intlConfig]);
}

0 comments on commit 31ab222

Please sign in to comment.