How to Re-render Svelte Components Using the {#key} Block

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call

In this guide, you'll learn how to use the {#key} block to force a Svelte component to re-render.

Step 1: Set up Your SvelteKit Project

  1. Create a new SvelteKit project:
npm create svelte@latest key-block
cd key-block
npm install
  1. Start the development server:
npm run dev

Step 2: Create a Svelte Component

Create a new Svelte component to re-render. For this example, we'll create a Clock.svelte component in the src/lib/ directory to display the current time.

<!-- src/lib/Clock.svelte -->
<script lang="ts">
	export let time;
</script>

<p>The current time is {time}</p>

Step 3: Use the {#key} Block

Import the Clock.svelte component into your src/routes/+page.svelte file and use the {#key} block to trigger a re-render whenever the time value changes:

<!-- src/routes/+page.svelte -->
<script lang="ts">
	import { onMount } from 'svelte';
	import Clock from '$lib/Clock.svelte';

	let time = new Date().toLocaleTimeString();

	function updateTime() {
		time = new Date().toLocaleTimeString();
	}

	onMount(() => {
		// Update the time every second
		const interval = setInterval(updateTime, 1000);

		// Clear interval when the component is destroyed
		return () => clearInterval(interval);
	});
</script>

<main>
	{#key time}
		<Clock {time} />
	{/key}
</main>

Explanation

Tips

Conclusion

You can now effectively use the {#key} block in Svelte to force component re-renders whenever necessary. Happy coding!

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call