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

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.

    toggled = false

{#key toggled}
    <Component />

<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.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

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:

    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
Copied to clipboard!
Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More