How to Force Rerender Components in Svelte

How to Force Rerender Components in Svelte

Using key blocks
Ferenc Almasi β€’ 2022 November 03 β€’ πŸ“– 2 min read
  • twitter
  • facebook

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>
    toggled = false
</script>

{#key toggled}
    <Component />
{/key}

<button on:click={() => toggled = !toggled}>Rerender component</button>
Using a key block to force rerender when a value changes
Copied to clipboard!

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>
Triggering rerender for only the affected parts
Copied to clipboard!
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended