I'm working on a Svelte 5 + SvelteKit project, and I need some advice regarding how to properly execute a specific piece of code every time a new URL is loaded.
For context, I have several pages that only differ in their URL identifier, for example:
Currently, my setup looks something like this:
/address/[id]/+page.svelte
<script>
import { onMount } from 'svelte';
let { data } = $props();
onMount(() => {
// This code runs only once when the +page.svelte is first loaded.
// It doesn't run again when navigating through these URLs: /address/21, /address/544, /address/611635
});
async function init() {
// I want this code to run every time a new URL is loaded,
// even if the +page.svelte file remains the same.
// For example: /address/21, /address/544, /address/611635
}
</script>
{#key data.addressID}
<div use:init>
<!-- HTML content -->
</div>
{/key}
I am currently using the #key block to regenerate the DOM for every new URL load and trigger the use:init directive, which runs the desired code.
While this works, I have heard in some podcasts and discussions that relying on the use: directive isn't always a good idea. Also, it feels like there should be a cleaner, more efficient solution to handle this scenario.
So my questions are:
Any advice or examples would be greatly appreciated. Thanks in advance!
You can get a persistent reference to the node via bind:this
and to execute code on navigation, you can use afterNavigate
.
A lifecycle function that runs the supplied
callback
when the current component mounts, and also whenever we navigate to a URL.
#key
destroys and re-creates content which can be expensive depending on what the content is, I would try to avoid it unless there is a good reason to use it/the alternatives are worse.