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. 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. 2. Why did Svelte 5 move from compiler-instrumented let reactivity 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. 3. How are $derived values 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. 4. Why does this effect run only once, even though state.value changes?

    let state = $state({ value: 0 });
    
    $effect(() => {
      console.log(state);
    });

    Correct answer: It depends on state itself and never reads state.value

    An effect reruns only when what it actually read changes. To log deep changes during development, use $inspect(state).

  5. 5. What does it mean that $effect dependencies 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. 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. 7. What is the cost of deep $state proxies, and how do you control it?

    Correct answer: Reads go through a proxy; use $state.raw for large data

    Only use $state for values that drive effects, deriveds or the template. Non-reactive data can stay in normal variables.

  8. 8. What does createSubscriber from svelte/reactivity solve?

    Correct answer: Subscribing to external sources only while something reads them

    It's how MediaQuery is built: the listener is attached when the value is read in an effect and removed when no effects depend on it.

  9. 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. 10. Why must $effect be created inside a component or another effect, and what is $effect.root for?

    Correct answer: Effects have an owner; $effect.root is a manual scope

    A root effect isn't cleaned up automatically, so you must call the returned cleanup function to avoid leaks.

  11. 11. How does Svelte 5 handle events like click and input for performance?

    Correct answer: Event delegation: one listener at the root of the app

    This matters when mixing with manually added listeners: stopPropagation in a native listener on an ancestor can stop delegated handlers from firing.

  12. 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 $derived instead. Use {#key} deliberately, e.g. to replay transitions.

  13. 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 await in <script>, $derived and markup

    It's opt-in because it's not yet considered stable. Combined with <svelte:boundary> it handles pending states.

  14. 14. What are "synchronized updates" in async Svelte?

    <p>{a} + {b} = {await add(a, b)}</p>

    Correct answer: The UI waits for add and then updates everything together

    Overlapping updates are allowed: a fast newer update can show while an older slow one is still pending.

  15. 15. Do independent await expressions 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. 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 a pending snippet

    The pending snippet is shown only on the first load. Subsequent updates keep the old UI, and $effect.pending() reports how many promises are in flight.

  17. 17. Which errors does <svelte:boundary> NOT catch?

    Correct answer: Errors in event handlers and setTimeout callbacks

    Handle those in the handler itself. The onerror prop can report caught errors to monitoring; failed receives error and reset.

  18. 18. What does $state.eager do 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. 19. How does Svelte render on the server?

    import { render } from "svelte/server";
    const { head, body } = render(App, { props: { user } });

    Correct answer: render produces HTML and hydrate attaches to it

    Effects and onMount don't run on the server. Code in <script> runs in both places, so it must be safe without window.

  20. 20. Why can MediaQuery or reading localStorage at 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. 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 = false the head would be filled only on the client, which is worse for SEO and link previews.

  22. 22. When does SvelteKit re-run a load function?

    Correct answer: When something it used changes, or on invalidate

    SvelteKit tracks which inputs each load touched. untrack excludes something from that tracking.

  23. 23. Why is an auth check only in +layout.server.js risky?

    Correct answer: Layout load may not re-run, and pages don't wait for it

    SvelteKit docs warn about this: a layout guard doesn't protect child data loads by itself.

  24. 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 depends and call invalidate

    Form actions with use:enhance invalidate all data automatically after a successful submission.

  25. 25. Why should load functions 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 data or pass it into context.

  26. 26. What does event.locals give you in SvelteKit?

    Correct answer: A per-request object set in handle

    Type it via App.Locals in app.d.ts. Because it's per request, it's safe for user data.

  27. 27. What is handleFetch used for?

    Correct answer: Modifying fetch requests made on the server

    It runs in hooks.server.js for server-side fetches; handle is for incoming requests.

  28. 28. What does the reroute hook 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. 29. What does handleError do, 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. 30. What does the transport hook 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. 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 await in components.

  32. 32. How do the remote function types differ?

    Correct answer: query reads, form submits, command mutates, prerender runs at build

    The form remote function covers the same use cases as form actions but can be used from any component.

  33. 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. 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. 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.origin sets the public origin behind proxies.

  36. 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 entries that returns the list of params

    Prerendered pages must render the same for every user; pages using form actions can't be prerendered.

  37. 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. 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. 39. What is page.form / the form prop after an action?

    Correct answer: The value returned by the last action

    Use it to show validation errors and keep submitted values.

  40. 40. How does use:enhance customization 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. 41. Where is SvelteKit configuration declared in SvelteKit 3?

    Correct answer: In vite.config.js, as options of the sveltekit() plugin

    Options that lived under kit.* are now top-level plugin options. Configuring through the Vite plugin was added in 2.62 to ease migration.

  42. 42. What replaced $app/stores in SvelteKit?

    Correct answer: $app/state, with fine-grained state based on runes

    Read page.url instead of $page.url. Changes to page are visible only in runes mode.

  43. 43. What happened to the $lib alias in SvelteKit 3?

    Correct answer: It became #lib, declared in package.json imports

    Vite and TypeScript resolve subpath imports natively. Imports now include file extensions, e.g. #lib/foo.js.

  44. 44. How do you migrate a project to SvelteKit 3 or a codebase to Svelte 5 syntax?

    Correct answer: With the sv migrate command

    Upgrading to the last 2.x first gives targeted deprecation warnings before the breaking changes.

  45. 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. 46. Where should private environment variables be read in SvelteKit 3?

    Correct answer: From $app/env/private, in server-only code

    Importing private env into client code fails the build, the same protection as for .server modules.

  47. 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. 48. Why does SvelteKit keep page components mounted when navigating between /blog/a and /blog/b?

    Correct answer: The route component is reused and only data changes

    let title = data.post.title would keep the old title; let title = $derived(data.post.title) updates. {#key} would force a remount, at a cost.

  49. 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. 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 load functions in parallel unless you await parent() too early.

  51. 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 Vite

    SvelteKit already splits code per route; dynamic imports help with heavy widgets inside a page.

  52. 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 ...rest onto the element lets consumers add attributes, handlers and attachments without the library knowing about them.

  53. 53. How does scoping CSS work, and what are its limits?

    Correct answer: A hash class is added; {@html} content needs :global

    Scoped selectors get extra specificity from the hash class. Custom elements mode uses Shadow DOM instead.

  54. 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. 55. Why test runes logic in files named *.svelte.test.js?

    Correct answer: The .svelte part makes the compiler process runes

    Combine with $effect.root and flushSync to test effects synchronously.

  56. 56. Which approach fits end-to-end testing of a SvelteKit app?

    Correct answer: Playwright against a built app with preview

    sv add playwright sets this up. Async server rendering and actions are best verified end to end.

  57. 57. What is a good way to debug unexpected re-runs in Svelte 5?

    Correct answer: $inspect.trace() at the top of the effect

    The trace shows which dependency changed, which usually reveals an accidental read.

  58. 58. What is wrong with deriving state from props like this in a reusable component?

    let { initial } = $props();
    let value = $state(initial);

    Correct answer: value captures only the initial prop value

    Sometimes capturing the initial value is intended (e.g. a form's default); then name it clearly, like initialValue.

  59. 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 generics attribute plus Snippet<[T]>

    Consumers then get type checking for the snippet's parameter based on the items passed in.

  60. 60. What is the difference between mount and hydrate?

    Correct answer: mount creates new DOM, hydrate reuses server DOM

    Effects (including onMount) don't run during the mount/hydrate call itself; call flushSync() to run them immediately, e.g. in tests.

  61. 61. Why would you return a promise from a server load instead 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. 62. What does updated from $app/state help 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. 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. 64. What does fromAction from svelte/attachments do?

    Correct answer: Converts a use: action into an attachment

    It eases gradual migration from actions while using libraries that haven't updated yet.

  65. 65. Why is mutating data received from load in a page component a bad idea?

    Correct answer: SvelteKit owns it and will replace it on the next load

    Treat data like props: compute with $derived, and use writable deriveds for optimistic UI.

  66. 66. What does event delegation in Svelte 5 mean for listeners added with addEventListener on window?

    Correct answer: A listener that stops propagation early can block delegated ones

    on from svelte/events preserves correct ordering relative to delegated handlers.

  67. 67. Why can't a $derived expression 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. 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 pending snippet is no longer used.

  69. 69. What is a risk of using $state in 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 $state fields are supported and keep the API surface small.

  70. 70. How does Svelte handle bind:value between a parent $state and a child $bindable prop?

    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. 71. Why might a SvelteKit page with heavy +layout.server.js data hurt navigation speed?

    Correct answer: Layout data tied to url re-runs often and blocks children

    Reading url.pathname or url.searchParams in a layout load makes it a dependency, so it re-runs on related navigations.

  72. 72. What does getRequestEvent from $app/server allow?

    Correct answer: Reading the current request event in shared server code

    Useful for helpers like requireUser() used across many server functions.

  73. 73. Why do SvelteKit form actions return 303 redirects or fail instead of rendering errors directly?

    Correct answer: To avoid resubmitting on reload and keep the page on errors

    With use:enhance the redirect is followed client-side and the UI updates without a full reload.

  74. 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 data changes; the instance is created once.

  75. 75. What does a prerender remote 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.