Ever felt your UI lag when nothing “should” be slow?
That’s when localizing re-renders works wonders. It’s not about micro-optimizations, it’s about owning your composition structure.
1) Split context responsibilities
const SetItemContext = createContext<Dispatch<number>>(() => {});
const ItemContext = createContext<number>(0);
export const Provider = ({ children }: { children: React.ReactNode }) => {
const [item, setItem] = useState(1);
return (
<SetItemContext.Provider value={setItem}>
<ItemContext.Provider value={item}>{children}</ItemContext.Provider>
</SetItemContext.Provider>
);
};
Consumers tied only to the setter won’t re-render on value change.
2) Optimize TanStack Query subscriptions
Avoid destructuring query results before returning them from your custom hooks.
// ❌ Causes all consumers to re-render
export const useUser = () => {
const { data, error, isLoading } = useQuery(...);
return { data, error, isLoading };
};
// ✅ Gives per-field subscription
export const useUser = () => {
const useQueryResult = useQuery(...);
return useQueryResult
}
// consumer 1 - loading indicator renderer
const { isLoading } = useUser()
// consumer 2 - data renderer
const { data } = useUser()
// consumer 3 - error tracker
const { error } = useUser()
Now data, error, and isLoading consumers re-render independently.
3) Render prop = localized reactivity
Move your stateful logic closer to where it’s used via render props or children. React will reuse the evaluated element if props are unchanged. No need for memo overkill.
const Component = () => {
const filledHeight = useCalculatedHeight(); // Imagine this changes frequently
return (
<div sx={{ height: `calc(100% - ${filledHeight}px` }}>
{/*
This NestedComponent will re-render EVERY TIME 'filledHeight' changes,
even if 'nestedProps' haven't changed.
React sees that the parent Component re-rendered, and by default,
it will re-render all its children.
*/}
<NestedComponent {...nestedProps} />
</div>
);
};
// This component now *receives* its child, rather than creating it
const PerformantComponent = ({ nestedComponent }) => {
const filledHeight = useCalculatedHeight(); // This still changes frequently
return (
<div sx={{ height: `calc(100% - ${filledHeight}px` }}>
{/*
Now, 'nestedComponent' is a PROP.
If the PARENT of PerformantComponent passes the *same* 'nestedComponent'
prop reference, React will NOT re-render it when 'filledHeight' changes.
It reuses the already evaluated element.
*/}
{nestedComponent}
</div>
);
};
Start with composition before you reach for memoization.
Good composition is performance.
Top comments (0)