Performance: beforeUpdate and afterUpdate
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 |
beforeUpdate lifecycle function in Svelte?beforeUpdate function runs right before the DOM changes are applied.afterUpdate runs after DOM updates, and onDestroy runs when the component is removed.beforeUpdate in a Svelte component?import { beforeUpdate } from 'svelte';beforeUpdate is called as a function with a callback: beforeUpdate(() => { ... });import { beforeUpdate, afterUpdate } from 'svelte';
let count = 0;
beforeUpdate(() => {
console.log('Before:', count);
});
afterUpdate(() => {
console.log('After:', count);
});
function increment() {
count += 1;
}increment() once?beforeUpdate callback runs before the DOM updates but after the state change. However, the console.log inside beforeUpdate logs the current value of count before the DOM updates, which is the updated value.afterUpdate callback runs after the DOM updates, logging the updated value of count.increment() is called, count is incremented to 1. Then beforeUpdate runs and logs Before: 0 because the DOM hasn't updated yet, but the variable has changed. Then afterUpdate runs and logs After: 1.import { beforeUpdate, afterUpdate } from 'svelte';
beforeUpdate = () => console.log('Before update');
afterUpdate(() => console.log('After update'));beforeUpdate, overwriting the imported function instead of calling it.afterUpdate is correctly called as a function with a callback.status right before the DOM updates and log the new status right after the DOM updates in a Svelte component. Which code snippet correctly achieves this?beforeUpdate to assign status = 'updating' before the DOM changes.afterUpdate to log the current status after the DOM updates.Pass the test and this pattern moves unknown