Cache computation results in React components to prevent unnecessary recalculations during re-renders, which can significantly impact application performance. Apply these optimization techniques in three key areas:
Cache computation results in React components to prevent unnecessary recalculations during re-renders, which can significantly impact application performance. Apply these optimization techniques in three key areas:
// Optimized approach import { createSelector } from ‘reselect’; const memoizedSelector = createSelector( [selectCurrentToolCall], (toolCall) => toolCall ); const currentToolCall = useAppSelector(memoizedSelector);
2. **Expensive calculations**: Move computations with O(n) or higher complexity outside render loops and cache them:
```tsx
// Suboptimal approach - O(n²) complexity
{history.map(item => {
const latestSummaryIndex = findLatestSummaryIndex(history);
// rest of render logic
})}
// Optimized approach - O(n) complexity
const latestSummaryIndex = useMemo(() =>
findLatestSummaryIndex(history),
[history]
);
{history.map(item => {
// use latestSummaryIndex
// rest of render logic
})}
<div style=>
// Optimized approach const fontSize = useFontSize(); <div style=> ```
When implementing these optimizations, focus on functions that perform expensive calculations or create new object references, especially those called frequently during renders or within loops.
Enter the URL of a public GitHub repository