Skip to main content
Lightning Jar - Web Studio Lightning Jar Wordmark

Findings No. 51

Initializing `$state` from props needs a `{#key}`, or one route's state leaks into the next

SvelteKit reuses a page component across param navigations, so $state initialized from props keeps the old route's value. Wrapping it in {#key data.routeId} remounts it.

CCRTA Website SvelteKit verified SvelteKit with Svelte 5 runes

$state(initialValueFromProps) captures the prop once, when the component mounts. SvelteKit reuses page components when only the route parameters change, so the component does not remount, and the old value stays.

On the CCRTA website, navigating client-side from one route page to another (say /ride/routes/5 to /ride/routes/6) left the schedule showing the previous route's selected stop. RouteSchedule had initialized its selected stop and search text from props, and the reused component never re-ran that initialization. Svelte's state_referenced_locally warning had been pointing at exactly this.

The fix wraps the component in {#key data.routeId}, so a change of route remounts it and its state starts fresh for the new route. Because the warning is correct in general and only wrong here because of the key, we silenced it with a svelte-ignore and a comment explaining that the key at the usage site is what makes it safe.

The general rule: capturing an initial value from props is a pattern only when something forces a remount, such as a {#key} on the identifying parameter. Without that, use a $derived instead, and document whichever you choose next to the other half.

Receipt: CCRTA Website commit 6af75b4 (RouteSchedule, {#key data.routeId}; FINDINGS.md, "Svelte 5 / SvelteKit").

Ask Eljay

Ask about the studio's work, research, packages, or writing. A few starters:

Answers come from this site's own content and link their sources. For anything that matters, email hello@lightningjar.com.