Split the Context
If we just need appContextValue. But the appContextValue itself changes too often, we can separate ThemeContext from the AppContext
function Button() {
let {theme} = useContext(ThemeContext);
// The rest of your rendering logic
return <ExpensiveTree className={theme} />;
}
Copy the code
Split components, put them in memo
function Button() {
let appContextValue = useContext(AppContext);
let theme = appContextValue.theme; // Your "selector"
return <ThemedButton theme={theme} />
}
const ThemedButton = memo(({ theme }) => {
// The rest of your rendering logic
return <ExpensiveTree className={theme} />;
});
Copy the code
Put components in useMemo
function Button() { let appContextValue = useContext(AppContext); let theme = appContextValue.theme; // Your "selector" return useMemo(() => { // The rest of your rendering logic return <ExpensiveTree className={theme} / >; }, [theme]) }Copy the code