Skip to content

Commit

Permalink
reset t if ns changes in useTranslation, fix #1517 (#1518)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrai committed Jun 14, 2022
1 parent aed8372 commit 47d9670
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/useTranslation.js
Expand Up @@ -2,6 +2,14 @@ import { useState, useEffect, useContext, useRef } from 'react';
import { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context';
import { warnOnce, loadNamespaces, hasLoadedNamespace } from './utils';

const usePrevious = (value, ignore) => {
const ref = useRef();
useEffect(() => {
ref.current = ignore ? ref.current : value;
}, [value, ignore]);
return ref.current;
};

export function useTranslation(ns, props = {}) {
// assert we have the needed i18nInstance
const { i18n: i18nFromProps } = props;
Expand Down Expand Up @@ -48,6 +56,9 @@ export function useTranslation(ns, props = {}) {
}
const [t, setT] = useState(getT);

const joinedNS = namespaces.join();
const previousJoinedNS = usePrevious(joinedNS);

const isMounted = useRef(true);
useEffect(() => {
const { bindI18n, bindI18nStore } = i18nOptions;
Expand All @@ -61,6 +72,10 @@ export function useTranslation(ns, props = {}) {
});
}

if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
setT(getT);
}

function boundReset() {
if (isMounted.current) setT(getT);
}
Expand All @@ -76,7 +91,7 @@ export function useTranslation(ns, props = {}) {
if (bindI18nStore && i18n)
bindI18nStore.split(' ').forEach((e) => i18n.store.off(e, boundReset));
};
}, [i18n, namespaces.join()]); // re-run effect whenever list of namespaces changes
}, [i18n, joinedNS]); // re-run effect whenever list of namespaces changes

// t is correctly initialized by useState hook. We only need to update it after i18n
// instance was replaced (for example in the provider).
Expand Down

0 comments on commit 47d9670

Please sign in to comment.