Performance: beforeUpdate and afterUpdate
MEDIUM IMPACT
These lifecycle hooks affect the rendering performance by running code before and after the DOM updates, impacting interaction responsiveness and visual stability.
import { beforeUpdate, afterUpdate } from 'svelte'; beforeUpdate(() => { // minimal logic, defer heavy work requestIdleCallback(() => { // heavy task deferred }); }); afterUpdate(() => { // batch DOM style changes or use CSS classes instead document.body.classList.add('updated'); });
import { beforeUpdate, afterUpdate } from 'svelte'; beforeUpdate(() => { // heavy synchronous task for(let i=0; i<1000000; i++) {} }); afterUpdate(() => { document.querySelectorAll('.item').forEach(el => { el.style.width = '100px'; }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous code in beforeUpdate/afterUpdate | Multiple DOM reads/writes | Multiple reflows triggered | High paint cost due to style changes | [X] Bad |
| Lightweight hooks with deferred heavy work | Minimal DOM operations | Single or no reflow | Low paint cost with CSS batching | [OK] Good |