0
0
SvelteHow-ToBeginner · 3 min read

How to Use afterUpdate in Svelte: Simple Guide and Example

In Svelte, use the afterUpdate function to run code after the component's DOM has updated. Import it from svelte and pass a callback that runs after every update cycle.
📐

Syntax

The afterUpdate function is imported from svelte and takes a callback function that runs after the DOM updates. It runs after every reactive update, allowing you to perform side effects based on the updated DOM.

The callback can optionally return a cleanup function that runs before the next update.

svelte
import { afterUpdate } from 'svelte';

afterUpdate(() => {
  // code to run after DOM updates
  return () => {
    // optional cleanup before next update
  };
});
💻

Example

This example shows a counter that updates a message after the DOM updates. The afterUpdate callback logs the updated count to the console every time the count changes.

svelte
<script>
  import { afterUpdate } from 'svelte';
  let count = 0;

  afterUpdate(() => {
    console.log(`Count updated to: ${count}`);
  });

  function increment() {
    count += 1;
  }
</script>

<button on:click={increment}>Increment</button>
<p>Count: {count}</p>
Output
Button labeled 'Increment' and text 'Count: 0' initially. Each click increases count and updates text, console logs 'Count updated to: X' after each update.
⚠️

Common Pitfalls

1. Running expensive code inside afterUpdate without conditions can hurt performance. Use checks inside the callback to run code only when needed.

2. Forgetting to clean up side effects can cause bugs. Return a cleanup function if you set timers or event listeners.

3. Using afterUpdate to update reactive variables directly can cause infinite loops. Avoid changing state inside afterUpdate without conditions.

svelte
import { afterUpdate } from 'svelte';

let count = 0;

// Wrong: updates count inside afterUpdate causing infinite loop
afterUpdate(() => {
  count += 1; // causes infinite updates
});

// Right: only log or run side effects without changing state
afterUpdate(() => {
  console.log(`Count is ${count}`);
});
📊

Quick Reference

FeatureDescription
Importimport { afterUpdate } from 'svelte';
PurposeRun code after DOM updates
CallbackFunction called after each update
CleanupReturn a function to clean up before next update
Use CaseSide effects depending on updated DOM

Key Takeaways

Use afterUpdate to run code after the component's DOM updates.
Avoid changing reactive state inside afterUpdate without conditions to prevent infinite loops.
Return a cleanup function from afterUpdate callback to clean side effects.
Use afterUpdate for side effects that depend on the updated DOM, like logging or animations.
Check conditions inside afterUpdate to avoid running expensive code unnecessarily.