0 day streak
javascript / intermediate
Snippet

Handling DOM Updates with the tick Function

The 'tick' function returns a promise that resolves as soon as any pending state changes have been applied to the DOM. This is essential when you need to interact with the DOM immediately after a state change.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { tick } from 'svelte';
let message = 'Original';
async function updateMessage() {
message = 'Updated Content';
// Svelte hasn't updated the DOM yet
await tick();
// Now the DOM is guaranteed to be in sync
console.log('DOM is updated');
}
svelte
Breakdown
1
message = 'Updated Content';
Change the state; Svelte schedules a DOM update but doesn't run it immediately.
2
await tick();
Wait for the microtask queue to clear and the DOM to be updated.