How to Force Rerender Components in Svelte

How to Force Rerender Components in Svelte

Using key blocks
Ferenc Almasi β€’ 2022 November 03 β€’ Read time 2 min read
Learn how you can easily force the recreation and rerender of Svelte components with the help of key blocks.
  • 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.

Copied to clipboard!
    import Component from './Component.svelte'

    let toggled = false

{#key toggled}
    <Component />

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

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:

Copied to clipboard!
    let count = 1;

<h1>Count: {count}</h1>
<button on:click={() => count += 1}>βž•</button>
<button on:click={() => count -= 1}>βž–</button>
Triggering rerender for only the affected parts
  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro



This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.