I'm using react-localization
for i18n that uses an object with a setLanguage
method. I'm trying to build a language switcher for it, but when I change the language, the component doesn't re-render with the updated object.
I've tried with useEffect
, useCallback
, useRef
. The only thing that works is useCallback
, and exporting the callback from my custom hook, then calling it when the component renders, which I think is very ugly and incorrect.
What's the proper way to mutate an object from a hook and have the component that uses it be re-rendered?
Here's the CodeSandbox I created to test this: https://codesandbox.io/s/react-localization-context-wfo2p2
translation.js
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState
} from "react";
const TranslationContext = createContext({
language: "fr",
setLanguage: () => null
});
const TranslationProvider = ({ children }) => {
const [language, setLanguage] = useState("fr");
return (
<TranslationContext.Provider value={{ language, setLanguage }}>
{children}
</TranslationContext.Provider>
);
};
const useTranslation = (_strings, key) => {
const { language, setLanguage } = useContext(TranslationContext);
const ref = useRef(_strings);
const cb = useCallback(() => _strings.setLanguage(language), [
language,
_strings
]);
useEffect(() => {
ref?.current?.setLanguage(language);
}, [language]);
return { language, cb, setLanguage };
};
export { useTranslation, TranslationProvider, TranslationContext };