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 CallIn 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
- Create a new SvelteKit project:
npm create svelte@latest key-block
cd key-block
npm install
- 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
- Import the Component: In
src/routes/+page.svelte, we import theClockcomponent. - Initialize State: We initialize the
timevariable with the current time. - Update Function: The
updateTimefunction updates thetimevariable with the current time. This function is called every second usingsetInterval. onMountLifecycle Hook: TheonMountfunction runs when the component is first mounted. Inside it, we set up an interval to callupdateTimeevery second and return a cleanup function to clear the interval when the component is destroyed.{#key}Block: The{#key}block is used to wrap theClockcomponent. Whenever thetimevariable changes, the entireClockcomponent will be destroyed and recreated, ensuring a complete re-render.
Tips
- State Preservation: The state of any content within the
{#key}block is reset as the contents are completely destroyed and re-created. - Complex Components: For more complex components, consider what state needs to be preserved and what should be reset on re-render.
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