0
0
Svelteframework~8 mins

Derived values with $: in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: Derived values with $:
MEDIUM IMPACT
This affects how efficiently the UI updates when reactive data changes, impacting interaction responsiveness and rendering speed.
Updating UI based on reactive data changes
Svelte
let count = 0;
$: doubled = count * 2; // reactive declaration

function increment() {
  count += 1;
}
Svelte automatically tracks dependencies and updates 'doubled' only when 'count' changes, batching DOM updates efficiently.
📈 Performance GainSingle reflow per change; reduces redundant calculations and improves input responsiveness.
Updating UI based on reactive data changes
Svelte
let count = 0;
let doubled;

function increment() {
  count += 1;
  doubled = count * 2; // manual update
}
Manually updating dependent values can cause inconsistent state and extra DOM updates if not carefully managed.
📉 Performance CostTriggers multiple reflows if DOM updates are not batched; increases chance of redundant calculations.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual updates of derived valuesMultiple updates per changeMultiple reflowsHigher paint cost[X] Bad
Using $: reactive declarationsMinimal updates, batchedSingle reflow per changeLower paint cost[OK] Good
Rendering Pipeline
Svelte's reactive declarations ($:) mark derived values that update automatically when dependencies change, triggering minimal DOM updates.
JavaScript Execution
Style Calculation
Layout
Paint
⚠️ BottleneckLayout and Paint stages due to unnecessary DOM updates if reactive declarations are not used properly.
Core Web Vital Affected
INP
This affects how efficiently the UI updates when reactive data changes, impacting interaction responsiveness and rendering speed.
Optimization Tips
1Use $: reactive declarations to automatically update derived values.
2Avoid manual updates of dependent state to prevent redundant DOM changes.
3Batch state changes to minimize reflows and paints for better responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using Svelte's $: reactive declarations for derived values?
AThey increase bundle size but improve rendering speed.
BThey prevent any DOM updates from happening.
CThey automatically update derived values only when dependencies change, reducing unnecessary DOM updates.
DThey delay updates until the user stops interacting.
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for multiple layout or paint events triggered by state changes.
What to look for: Fewer layout and paint events indicate efficient reactive updates; many repeated events suggest manual or redundant updates.