Performance: Why lifecycle hooks run code at key moments
MEDIUM IMPACT
This affects how efficiently code runs during component creation, update, and destruction, impacting interaction responsiveness and visual stability.
import { onMount, onDestroy } from 'svelte'; onMount(() => { expensiveCalculation(); }); onDestroy(() => { cleanupResources(); }); function expensiveCalculation() { // heavy logic } function cleanupResources() { // cleanup logic }
import { onMount } from 'svelte'; // Running heavy code repeatedly inside reactive statements instead of lifecycle hooks $: { expensiveCalculation(); } function expensiveCalculation() { // heavy logic }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy code in reactive statements | Multiple per state change | Multiple reflows per update | High paint cost due to frequent layout changes | [X] Bad |
| Heavy code in onMount/onDestroy hooks | Single or few operations | Single reflow on mount/destroy | Low paint cost, stable layout | [OK] Good |