Svelte Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What model does Svelte 5 reactivity use under the hood?
Correct answer: Signals: reads register dependencies, writes schedule affected effects
Template expressions are effects too. Runes are the syntax over this runtime; Svelte 4 instead relied on the compiler instrumenting assignments.
2. Why did Svelte 5 move from compiler-instrumented
letreactivity to runes?Correct answer: Old reactivity worked only at the top level; runes are explicit everywhere
With
$:statements dependencies were determined statically and only at compile time; runes track them at runtime, including through function calls.3. How are
$derivedvalues evaluated?Correct answer: Lazily and memoized: recalculated on read after a dependency changes
Svelte uses push-pull reactivity: changes mark dependents dirty (push), values are recomputed on read (pull). Equal results don't propagate.
4. Why does this effect run only once, even though
state.valuechanges?let state = $state({ value: 0 }); $effect(() => { console.log(state); });Correct answer: It depends on
stateitself and never readsstate.valueAn effect reruns only when what it actually read changes. To log deep changes during development, use
$inspect(state).5. What does it mean that
$effectdependencies are dynamic?$effect(() => { if (enabled) draw(color); });Correct answer: Only values read in the last run count as dependencies
This is precise and efficient, but it's also why conditionally read state may seem "not tracked".
6. What happens with updates batched in Svelte 5?
count = 1; count = 2; name = "Ann";Correct answer: Effects run once, in a microtask after the synchronous code, with the final values
Batching avoids wasted work and intermediate states.
flushSync()applies updates immediately when needed.7. What is the cost of deep
$stateproxies, and how do you control it?Correct answer: Reads go through a proxy; use
$state.rawfor large dataOnly use
$statefor values that drive effects, deriveds or the template. Non-reactive data can stay in normal variables.8. What does
createSubscriberfromsvelte/reactivitysolve?Correct answer: Subscribing to external sources only while something reads them
It's how
MediaQueryis built: the listener is attached when the value is read in an effect and removed when no effects depend on it.9. What does
$effect.tracking()return?Correct answer: Whether the code runs in a tracking context
Reading a value outside tracking context can't subscribe, so a library may return a snapshot instead.
10. Why must
$effectbe created inside a component or another effect, and what is$effect.rootfor?Correct answer: Effects have an owner;
$effect.rootis a manual scopeA root effect isn't cleaned up automatically, so you must call the returned cleanup function to avoid leaks.
11. How does Svelte 5 handle events like
clickandinputfor performance?Correct answer: Event delegation: one listener at the root of the app
This matters when mixing with manually added listeners:
stopPropagationin a native listener on an ancestor can stop delegated handlers from firing.12. Why is a
{#key}block an expensive way to re-run child logic?Correct answer: It recreates everything inside, losing state and DOM
Wrap the dependent computation in
$derivedinstead. Use{#key}deliberately, e.g. to replay transitions.13. What does experimental async Svelte (5.36+) allow?
<script> let { id } = $props(); const user = $derived(await getUser(id)); </script> <h1>{user.name}</h1>Correct answer: Using
awaitin<script>,$derivedand markupIt's opt-in because it's not yet considered stable. Combined with
<svelte:boundary>it handles pending states.14. What are "synchronized updates" in async Svelte?
<p>{a} + {b} = {await add(a, b)}</p>Correct answer: The UI waits for
addand then updates everything togetherOverlapping updates are allowed: a fast newer update can show while an older slow one is still pending.
15. Do independent
awaitexpressions in markup run sequentially?<p>{await one(x)}</p> <p>{await two(y)}</p>Correct answer: No: independent expressions run in parallel
Sequential
awaits in<script>or inside a function behave like normal JavaScript, so be careful not to create waterfalls there.16. How do you show a loading state with async Svelte?
<svelte:boundary> <Profile /> {#snippet pending()} <Spinner /> {/snippet} </svelte:boundary>Correct answer:
<svelte:boundary>with apendingsnippetThe
pendingsnippet is shown only on the first load. Subsequent updates keep the old UI, and$effect.pending()reports how many promises are in flight.17. Which errors does
<svelte:boundary>NOT catch?Correct answer: Errors in event handlers and
setTimeoutcallbacksHandle those in the handler itself. The
onerrorprop can report caught errors to monitoring;failedreceiveserrorandreset.18. What does
$state.eagerdo in async Svelte?<a href="/about" aria-current={$state.eager(pathname) === "/about" ? "page" : null}>About</a>Correct answer: Shows the new value at once while async updates are pending
Use it sparingly, only for feedback to user actions; normally letting Svelte coordinate updates gives a better result.
19. How does Svelte render on the server?
import { render } from "svelte/server"; const { head, body } = render(App, { props: { user } });Correct answer:
renderproduces HTML andhydrateattaches to itEffects and
onMountdon't run on the server. Code in<script>runs in both places, so it must be safe withoutwindow.20. Why can
MediaQueryor readinglocalStorageat component init cause problems with SSR?Correct answer: The server can't know the value, so the HTML may differ
Prefer CSS for responsive layout, read browser-only APIs in effects, or store preferences in cookies so the server can use them.
21. Why is
<svelte:head>content important for SvelteKit SEO?Correct answer: It is in the server HTML, so crawlers see it without JS
With
ssr = falsethe head would be filled only on the client, which is worse for SEO and link previews.22. When does SvelteKit re-run a
loadfunction?Correct answer: When something it used changes, or on
invalidateSvelteKit tracks which inputs each
loadtouched.untrackexcludes something from that tracking.23. Why is an auth check only in
+layout.server.jsrisky?Correct answer: Layout
loadmay not re-run, and pages don't wait for itSvelteKit docs warn about this: a layout guard doesn't protect child data loads by itself.
24. How do you trigger a reload of specific data after a mutation?
// +page.js export async function load({ fetch, depends }) { depends("app:cart"); return { cart: await (await fetch("/api/cart")).json() }; } // somewhere in the UI await invalidate("app:cart");Correct answer: Declare it with
dependsand callinvalidateForm actions with
use:enhanceinvalidate all data automatically after a successful submission.25. Why should
loadfunctions be free of side effects?// +page.js import { user } from "./state.svelte.js"; export async function load({ fetch }) { user.current = await (await fetch("/api/user")).json(); }Correct answer: Writing shared state there leaks data between users
Return the data and let components read it via
dataor pass it into context.26. What does
event.localsgive you in SvelteKit?Correct answer: A per-request object set in
handleType it via
App.Localsinapp.d.ts. Because it's per request, it's safe for user data.27. What is
handleFetchused for?Correct answer: Modifying
fetchrequests made on the serverIt runs in
hooks.server.jsfor server-side fetches;handleis for incoming requests.28. What does the
reroutehook do?Correct answer: Maps a URL to a route without changing the address bar
It's a universal hook in
hooks.js. Unlike a redirect, the user still sees the original URL.29. What does
handleErrordo, and why shouldn't it expose details?Correct answer: Logs unexpected errors and returns a safe shape to users
Expected errors created with
error()carry user-facing messages; unexpected ones should show a generic message.30. What does the
transporthook allow?Correct answer: Passing custom types across the server/client boundary
By default only devalue-serializable values can cross the boundary from server loads and actions.
31. What are SvelteKit remote functions?
Correct answer: Type-safe, experimental server functions called from components
They always run on the server, so they can use databases and secrets, and pair with async Svelte's
awaitin components.32. How do the remote function types differ?
Correct answer:
queryreads,formsubmits,commandmutates,prerenderruns at buildThe
formremote function covers the same use cases as form actions but can be used from any component.33. What is a single-flight mutation in remote functions?
Correct answer: The server returns fresh query data with the mutation response
It avoids the classic "mutate, then refetch" waterfall.
34. Why should remote function arguments be validated?
Correct answer: Anyone can call them over HTTP, so input must be checked
Types disappear at runtime; validation protects the server from malformed or malicious input.
35. How does SvelteKit protect form actions from CSRF?
Correct answer: It checks the origin and rejects cross-origin POSTs
In SvelteKit 3 trusted external origins are configured with
csrf.trustedOrigins;paths.originsets the public origin behind proxies.36. How do you prerender dynamic routes like
/blog/[slug]?export const prerender = true; export function entries() { return [{ slug: "hello" }, { slug: "world" }]; }Correct answer: Export
entriesthat returns the list of paramsPrerendered pages must render the same for every user; pages using form actions can't be prerendered.
37. What is the trade-off of making a SvelteKit app an SPA with a fallback page?
Correct answer: No server is needed, but first load and SEO get worse
Prefer prerendering where possible and keep SPA mode for apps behind a login or without a server.
38. Why are form actions a good default for mutations in SvelteKit?
Correct answer: They work without JavaScript and use web standards
Progressive enhancement keeps forms usable on slow devices, before hydration and when JavaScript fails.
39. What is
page.form/ theformprop after an action?Correct answer: The value returned by the last action
Use it to show validation errors and keep submitted values.
40. How does
use:enhancecustomization work?<form method="POST" use:enhance={({ formData, cancel }) => { submitting = true; return async ({ result, update }) => { submitting = false; await update(); }; }}>Correct answer: The outer function runs before submit, its callback after
Skipping
update()lets you handle results fully yourself, for example to avoid resetting the form.41. Where is SvelteKit configuration declared in SvelteKit 3?
Correct answer: In
vite.config.js, as options of thesveltekit()pluginOptions that lived under
kit.*are now top-level plugin options. Configuring through the Vite plugin was added in 2.62 to ease migration.42. What replaced
$app/storesin SvelteKit?Correct answer:
$app/state, with fine-grained state based on runesRead
page.urlinstead of$page.url. Changes topageare visible only in runes mode.43. What happened to the
$libalias in SvelteKit 3?Correct answer: It became
#lib, declared inpackage.jsonimportsVite and TypeScript resolve subpath imports natively. Imports now include file extensions, e.g.
#lib/foo.js.44. How do you migrate a project to SvelteKit 3 or a codebase to Svelte 5 syntax?
Correct answer: With the
sv migratecommandUpgrading to the last 2.x first gives targeted deprecation warnings before the breaking changes.
45. How can you migrate a large Svelte 4 app to Svelte 5 gradually?
Correct answer: Components without runes run in legacy mode, so go file by file
A component switches to runes mode as soon as it uses a rune, or with
<svelte:options runes />.46. Where should private environment variables be read in SvelteKit 3?
Correct answer: From
$app/env/private, in server-only codeImporting private env into client code fails the build, the same protection as for
.servermodules.47. How do you share state per request in a SvelteKit app safely?
Correct answer: Create it in the component tree and provide it via context
Each server render gets its own component tree and context, so data doesn't leak between users.
48. Why does SvelteKit keep page components mounted when navigating between
/blog/aand/blog/b?Correct answer: The route component is reused and only
datachangeslet title = data.post.titlewould keep the old title;let title = $derived(data.post.title)updates.{#key}would force a remount, at a cost.49. Where should UI state like filters or the current tab live if it must survive reloads and be shareable?
Correct answer: In the URL, as search params
URL state works with SSR, back/forward navigation and copy-pasted links.
50. What is the main performance advice for data loading in SvelteKit?
Correct answer: Avoid waterfalls: run independent requests in parallel
SvelteKit runs layout and page
loadfunctions in parallel unless youawait parent()too early.51. How can you make a code-heavy component load only when needed?
{#await import("./Chart.svelte") then { default: Chart }} <Chart data={stats} /> {/await}Correct answer: With a dynamic
import(), split by ViteSvelteKit already splits code per route; dynamic imports help with heavy widgets inside a page.
52. What should you consider when designing a Svelte component library?
Correct answer: Typed props, rest props on the root, CSS variables for themes
Spreading
...restonto the element lets consumers add attributes, handlers and attachments without the library knowing about them.53. How does scoping CSS work, and what are its limits?
Correct answer: A hash class is added;
{@html}content needs:globalScoped selectors get extra specificity from the hash class. Custom elements mode uses Shadow DOM instead.
54. What does
<svelte:options customElement>change about styling and props?Correct answer: Styles go into the shadow root, props become attributes
Custom elements are useful for embedding Svelte widgets in other frameworks, with some limitations around SSR and slots.
55. Why test runes logic in files named
*.svelte.test.js?Correct answer: The
.sveltepart makes the compiler process runesCombine with
$effect.rootandflushSyncto test effects synchronously.56. Which approach fits end-to-end testing of a SvelteKit app?
Correct answer: Playwright against a built app with
previewsv add playwrightsets this up. Async server rendering and actions are best verified end to end.57. What is a good way to debug unexpected re-runs in Svelte 5?
Correct answer:
$inspect.trace()at the top of the effectThe trace shows which dependency changed, which usually reveals an accidental read.
58. What is wrong with deriving state from props like this in a reusable component?
let { initial } = $props(); let value = $state(initial);Correct answer:
valuecaptures only the initial prop valueSometimes capturing the initial value is intended (e.g. a form's default); then name it clearly, like
initialValue.59. How do you type a component that accepts a generic list and a row snippet?
<script lang="ts" generics="T"> import type { Snippet } from "svelte"; let { items, row }: { items: T[]; row: Snippet<[T]> } = $props(); </script>Correct answer: The
genericsattribute plusSnippet<[T]>Consumers then get type checking for the snippet's parameter based on the items passed in.
60. What is the difference between
mountandhydrate?Correct answer:
mountcreates new DOM,hydratereuses server DOMEffects (including
onMount) don't run during themount/hydratecall itself; callflushSync()to run them immediately, e.g. in tests.61. Why would you return a promise from a server
loadinstead of awaiting everything?Correct answer: To stream slow data after the initial HTML
Top-level awaited data blocks rendering; unawaited promises are serialized and resolved on the client as they arrive.
62. What does
updatedfrom$app/statehelp with?Correct answer: Detecting that a new app version was deployed
In SvelteKit 3 the version check polls periodically by default, so long-open tabs learn about new deployments.
63. When is Svelte a particularly good fit compared to larger frameworks?
Correct answer: Performance-sensitive or embedded UIs with small bundles
Trade-offs include a smaller ecosystem and fewer developers on the market compared to React; consider hiring and libraries too.
64. What does
fromActionfromsvelte/attachmentsdo?Correct answer: Converts a
use:action into an attachmentIt eases gradual migration from actions while using libraries that haven't updated yet.
65. Why is mutating
datareceived fromloadin a page component a bad idea?Correct answer: SvelteKit owns it and will replace it on the next load
Treat
datalike props: compute with$derived, and use writable deriveds for optimistic UI.66. What does event delegation in Svelte 5 mean for listeners added with
addEventListeneronwindow?Correct answer: A listener that stops propagation early can block delegated ones
onfromsvelte/eventspreserves correct ordering relative to delegated handlers.67. Why can't a
$derivedexpression change state?let count = $state(0); let doubled = $derived(count++ * 2); // ?Correct answer: Deriveds must be pure, so Svelte throws on such writes
Side effects belong in event handlers, or, as a last resort, in effects.
68. What does
$effect.pending()return in async Svelte?{#if $effect.pending()} <p>Updating…</p> {/if}Correct answer: The number of promises pending in the current boundary
It's the way to show progress for updates after the first load, when the boundary's
pendingsnippet is no longer used.69. What is a risk of using
$statein a class field that is exposed as a public mutable property in a library?Correct answer: Any consumer can change it, which breaks invariants
Private
$statefields are supported and keep the API surface small.70. How does Svelte handle
bind:valuebetween a parent$stateand a child$bindableprop?Correct answer: The child reads and writes the parent's state through it
Explicit two-way contracts make it obvious which components may change which state.
71. Why might a SvelteKit page with heavy
+layout.server.jsdata hurt navigation speed?Correct answer: Layout data tied to
urlre-runs often and blocks childrenReading
url.pathnameorurl.searchParamsin a layout load makes it a dependency, so it re-runs on related navigations.72. What does
getRequestEventfrom$app/serverallow?Correct answer: Reading the current request event in shared server code
Useful for helpers like
requireUser()used across many server functions.73. Why do SvelteKit form actions return 303 redirects or
failinstead of rendering errors directly?Correct answer: To avoid resubmitting on reload and keep the page on errors
With
use:enhancethe redirect is followed client-side and the UI updates without a full reload.74. How do you integrate an imperative third-party library (e.g. a chart) cleanly in Svelte 5?
<div {@attach (node) => { const chart = createChart(node, options); $effect(() => chart.update(data)); return () => chart.destroy(); }}></div>Correct answer: With an attachment that creates and destroys the instance
Only the nested effect re-runs on
datachanges; the instance is created once.75. What does a
prerenderremote function do?Correct answer: Reads data at build time and serves it as static assets
It suits data that changes only on deploy, such as docs or a product catalogue.