Table of Contents
Get this article emailed to you .
: You can force re-rendering of a Svelte component by wrapping it in a
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
onMountlifecycle 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
block in Svelte
The key block in Svelte is a logic block, just like
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:
component will be destroyed and recreated every time the
variable changes. That means if you have an
lifecycle function in
, it will be called again every time
This might be useful when your component renders something like a chart that's being initialized in
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:
element will be destroyed and recreated every time the
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!