Reactive Blocks in Svelte
- 1 minute read
Svelte offers reactive statements, which are used to reactively run a given statement each time a variable changes.
But Svelte also offers a key block, which is used to reactively reload markup each time a variable changes.
For example, in the below snippet, each time the count
variable changes, a new paragraph is rendered:
<script>
let count = 0;
</script>
{#key count}
<p>This entire paragraph will reload each time <code>count</code> changes!</p>
{/key}
<button on:click={count++}>Click me!</button>
This can be paritcularly useful when regularly fetching data from a particular endpoint throughout the lifecycle of the page.
And it also works with components, too. In the below snippet, each time the exampleValue
variable changes, a new ExampleComponent
is instantiated:
{#key exampleValue}
<ExampleComponent />
{/key}
Conclusion
Anyway, hopefully you found this useful! Personally, I don’t find myself using the key
block too much, but there are times when it sure does come in handy.