0
0
Angularframework~8 mins

Selectors for derived state in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: Selectors for derived state
MEDIUM IMPACT
This affects how quickly the UI updates when state changes and how much CPU is used during rendering.
Calculating derived state from a global store to update UI
Angular
const selectActiveCount = createSelector(
  (state) => state.items,
  (items) => items.filter(item => item.active).length
);
const derivedValue = store.select(selectActiveCount);
Memoizes the filtered count, recalculating only when items change, reducing unnecessary work.
📈 Performance Gainreduces recalculations and re-renders, improving input responsiveness (INP)
Calculating derived state from a global store to update UI
Angular
const derivedValue = store.select(state => {
  return state.items.filter(item => item.active).length;
});
This recalculates the filtered list on every state change, even if unrelated parts of the state update.
📉 Performance Costtriggers multiple recalculations and re-renders, increasing CPU usage and slowing interaction
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Non-memoized selectorMany recalculationsMultiple reflows due to frequent updatesHigh paint cost from unnecessary renders[X] Bad
Memoized selector with createSelectorMinimal recalculationsSingle reflow per relevant state changeLower paint cost from fewer renders[OK] Good
Rendering Pipeline
Selectors compute derived data before Angular runs change detection. Efficient selectors reduce the work Angular must do during the Layout and Paint stages.
Style Calculation
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint stages due to unnecessary re-renders triggered by non-memoized selectors
Core Web Vital Affected
INP
This affects how quickly the UI updates when state changes and how much CPU is used during rendering.
Optimization Tips
1Always memoize selectors to avoid unnecessary recalculations.
2Use createSelector from Angular's store to build efficient selectors.
3Avoid inline selector functions inside components to prevent repeated work.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using memoized selectors in Angular?
AThey prevent unnecessary recalculations and reduce component re-renders.
BThey increase the size of the JavaScript bundle.
CThey delay the initial page load.
DThey automatically cache HTTP requests.
DevTools: Performance
How to check: Record a performance profile while interacting with the app. Look for frequent recalculations or component re-renders in the flame chart.
What to look for: High CPU usage spikes or repeated re-rendering of components indicate inefficient selectors.