Skip to content

Commit

Permalink
Fix/bug 1691 make returned t function identical upon second effect ru…
Browse files Browse the repository at this point in the history
…n in strict mode (#1716)

* fix: (pre-cleanup) bug 1691 use memoization of fixedT function

* style: bug 1691 debug cleanup: use memoization of fixedT function

* build: bug 1691 run npm build
  • Loading branch information
timheilman committed Feb 4, 2024
1 parent 0321c04 commit f8a4e19
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 15 deletions.
15 changes: 11 additions & 4 deletions react-i18next.js
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,12 @@
}, [value, ignore]);
return ref.current;
};
function alwaysNewT(i18n, language, namespace, keyPrefix) {
return i18n.getFixedT(language, namespace, keyPrefix);
}
function useMemoizedT(i18n, language, namespace, keyPrefix) {
return react.useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
}
function useTranslation(ns) {
let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
Expand Down Expand Up @@ -650,9 +656,8 @@
namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];
if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n, i18nOptions));
function getT() {
return i18n.getFixedT(props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
}
const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix);
const getT = () => memoGetT;
const [t, setT] = react.useState(getT);
let joinedNS = namespaces.join();
if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
Expand All @@ -671,7 +676,9 @@
});
} else {
loadNamespaces(i18n, namespaces, () => {
if (isMounted.current) setT(getT);
if (isMounted.current) {
setT(() => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0], keyPrefix));
}
});
}
}
Expand Down

0 comments on commit f8a4e19

Please sign in to comment.