How to re-render Svelte components?
If you have been using Svelte for enough time, you've probably come across one of the following situations:
You have a component that needs to be re-rendered when a prop changes.
You want your
onMountlifecycle function to be called again on certain conditions.You want to force a re-render of a component from a parent component.
In this article, we'll see how to achieve these with the native Svelte logic {#key ...} block.
The {#key ...} block in Svelte
The key block in Svelte is a logic block, just like {#if ...} or {#each ...}.
It basically destroys and recreates the block's content when the value of the expression passed to it changes.
For example, if you have the following code:
<script lang="ts">
let count = 0;
</script>
<button on:click={() => count++}>Click me</button>
{#key count}
<SomeComponent count={count} />
{/key}The SomeComponent component will be destroyed and recreated every time the count variable changes. That means if you have an onMount lifecycle function in SomeComponent, it will be called again every time count changes.
This might be useful when your component renders something like a chart that's being initialized in onMount with some data. If the data changes, you want the chart to be reinitialized with the new data.
The key block works not only on components but also on any markup you put inside. For example, if you have the following code:
<script lang="ts">
let count = 0;
</script>
<button on:click={() => count++}>Click me</button>
{#key count}
<p>{count}</p>
{/key}The p element will be destroyed and recreated every time the count variable changes as well.