How to Force Rerender Components in Svelte
In order to reflect changes in the state when working with Svelte, we need to use assignments. Svelte's reactivity is triggered by assignments.
However, there could be some use cases when we specifically need to rerender an entire component. To force rerender in Svelte, we can wrap the component into a key
block.
<script>
import Component from './Component.svelte'
let toggled = false
</script>
{#key toggled}
<Component />
{/key}
<button on:click={() => toggled = !toggled}>Rerender component</button>
This is a special block specifically made for this use case. The key
block expects a value to be passed. Anytime the value changes, the component(s) inside the key
block will be destroyed and recreated. This will cause the component to be re-rendered.
This can be useful for example when we want to play transitions of a component whenever the value passed to the key
block changes.
It's important to mention that for most use cases, you want to use assignments in order to trigger reactivity and update the DOM.
On the other hand, if we just need to update the DOM according to state changes, we can simply use an assignment in order to trigger a rerender for those parts only that are affected. For example:
<script>
let count = 1;
</script>
<h1>Count: {count}</h1>
<button on:click={() => count += 1}>β</button>
<button on:click={() => count -= 1}>β</button>
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: