I was looking at the answers of this post concerning the way to Update Context from a Nested Component and I was wondering...
Given this React context:
const LanguageContext = React.createContext({
language: "en",
setLanguage: () => {}
});
Aren't they missing an optimization when doing:
const App = () => {
const [language, setLanguage] = useState("en");
const value = { language, setLanguage }; // new object on every render
return (
<LanguageContext.Provider value={value}>
...
);
};
As the Context documentation states, there are some caveats.
You should lift the context object {value, setter}. It would avoid unwanted rerendering, even if this is quite unlikely to happen since the providers are at the top of the application.
Shouldn't it be:
const App = () => {
const [language, setLanguage] = useState("en");
const value = useMemo(() => ({ language, setLanguage }), [language, setLanguage])
return (
<LanguageContext.Provider value={value}>
...
);
};
This way the context value is updated only when its value change, and not when the component rerender.