πŸŽ‰ We just launched our new React course! Get it with 20% off! πŸŽ‰
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
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

Recommended