На ответ "как предотвратить перезагрузку компонента при изменении КОНТЕКСТА?" Перепишите свой функциональный компонент на компонент класса. Затем вы можете передать свойства своему компоненту и использовать shouldComponentUpdate, чтобы вручную заставить этот компонент не обновляться при изменении свойств. И не используйте useContext или contextType в этом компоненте. Ниже приведен простой пример:
import React, { useState, useContext, createContext } from "react";
const ThemeContext = createContext();
const themes = {
dark: {
color: "white",
backgroundColor: "rgb(21, 21, 21)"
},
light: {
color: "rgb(21, 21, 21)",
backgroundColor: "white"
}
};
class Button extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (this.props.theme !== nextProps.theme) {
return false;
}
return true;
}
render() {
const { toggleTheme, theme } = this.props;
console.log("render");
return (
<button onClick={toggleTheme} style={themes[theme]}>
Button
</button>
);
}
}
const ThemeButton = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return <Button theme={theme} toggleTheme={toggleTheme} />;
};
function App() {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
if (theme === "dark") setTheme("light");
if (theme === "light") setTheme("dark");
};
return (
<>
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<ThemeButton />
</ThemeContext.Provider>
</>
);
}
export default App;