Skip to content

Commit

Permalink
performance: cache Intl instances
Browse files Browse the repository at this point in the history
  • Loading branch information
zbigg committed Jul 26, 2024
1 parent 0e83a7b commit 2f2d7b3
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions packages/react-ui/src/hooks/useImperativeIntl.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { createIntl, createIntlCache } from 'react-intl';
import { messages } from '../localization';
import { useMemo } from 'react';
import {
flattenMessages,
findMatchingMessagesLocale,
Expand All @@ -9,21 +8,33 @@ import {

const cache = createIntlCache();

let lastIntlConfig;
let cachedC4rIntl;

export default function useImperativeIntl(intlConfig) {
return useMemo(() => {
if (!cachedC4rIntl || lastIntlConfig !== intlConfig) {
// this is very naive cache that bases on 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
const locale = intlConfig?.locale || DEFAULT_LOCALE;
const messagesLocale = findMatchingMessagesLocale(locale, messages);
const intMessages = {
...(messages[messagesLocale] || {}),
...(intlConfig?.messages || {})
};

return createIntl(
console.time('flattenMessages');
const combinedMessages = flattenMessages(intMessages);
console.time('flattenMessages');
cachedC4rIntl = createIntl(
{
locale,
messages: flattenMessages(intMessages)
messages: combinedMessages
},
cache
);
}, [intlConfig]);
lastIntlConfig = intlConfig;
}
return cachedC4rIntl;
}

0 comments on commit 2f2d7b3

Please sign in to comment.