2
votes

When im using svelte-kits routing system, I can create dynamics pages using [page].svelte for example, that will be rendered when I'm calling localhost:3000/foo. However when I'm navigating from localhost:3000/foo to localhost:3000/bar, the onMount() function is not called (I guess for performance reasons).

I can work around this issue by wrapping all relevant stuff in a {#key ... } expression, but is there any way to "remount" the page?

Thenks for helping me out :)

1
Any particular reason why you would want to remount? If you have actions that you want to trigger when page changes, you can put all these actions inside a function and call that function when page updates with a reactive statement that is dependent on page, for example: $: doRefresh(page). - Thomas Hennes
Maybe since I'm coming from other libraries, I'm still used to this convention, but your suggestion is also an elegant way. As @Bob Fanger mentioned, rarely I had some issues with third party libraries (p5js) where a canvas element was not fully removed, leading to performance issues. There it seemed easier to just fully 'remount' the page. - derschiw
That's a fair assessment, and for these situations {#key} would indeed be the right choice. - Thomas Hennes

1 Answers

3
votes

The onMount is not called, but the props are being updated.
This allows the new data to flow to the existing dom elements and the browser doesn't have to regenerate an entirely new page/component.

If there is state calculated based on these props, make sure that those are inside reactive statements and not just inside the onMount.

In some situation (with third-party code) it's more convenient to remount the component, and in those cases you'll use the {#key} block you mentioned.