How to re-render Svelte components?

Justin's profile pic

Justin Ahinon

Last updated on

Enter your email to get this article emailed to you

tl;dr : You can force re-rendering of a Svelte component by wrapping it in a {#key ...} block and passing a value that changes every time you want to re-render it.

If you have been using Svelte for enough time, you've probably come across one of the following situations:

  • You have a component that needs to be re-rendered when a prop changes.

  • You want your  onMount  lifecycle function to be called again on certain conditions.

  • You want to force a re-render of a component from a parent component.

In this article, we'll see how to achieve these with the native Svelte logic  {#key ...} {#key ...}  block.

The  {#key ...}  block in Svelte

The key block in Svelte is a logic block, just like  {#if ...}  or  {#each ...} .

It basically destroys and recreates the block's content when the value of the expression passed to it changes .

For example, if you have the following code:

SVELTE

The  SomeComponent  component will be destroyed and recreated every time the  count  variable changes. That means if you have an  onMount  lifecycle function in  SomeComponent , it will be called again every time  count  changes.

This might be useful when your component renders something like a chart that's being initialized in  onMount  with some data. If the data changes, you want the chart to be reinitialized with the new data.

The key block works not only on components but also on any markup you put inside. For example, if you have the following code:

SVELTE

The  p  element will be destroyed and recreated every time the  count  variable changes as well.

Get help with your Svelte or SvelteKit code

Got a Svelte/Sveltekit bug giving you headaches? I’ve been there!

Book a free 15 min consultation call, and I’ll review your code base and give you personalized feedback on your code.

P.S. If you have a bigger problem that may need more than 15 minutes, you can also pick my brain for a small fee. 😊 But that’s up to you!