How to Use afterUpdate in Svelte: Simple Guide and Example
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.
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.
<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>
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.
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
| Feature | Description |
|---|---|
| Import | import { afterUpdate } from 'svelte'; |
| Purpose | Run code after DOM updates |
| Callback | Function called after each update |
| Cleanup | Return a function to clean up before next update |
| Use Case | Side effects depending on updated DOM |