Svelte Middle 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. When should you use $derived.by instead of $derived?

    let total = $derived.by(() => {
      let sum = 0;
      for (const item of cart) sum += item.price * item.qty;
      return sum;
    });

    Correct answer: When the computation needs several statements

    $derived(expr) is equivalent to $derived.by(() => expr). The function must be free of side effects.

  2. 2. Can you assign to a $derived value (Svelte 5.25+)?

    let { post } = $props();
    let likes = $derived(post.likes);
    
    async function like() {
      likes += 1; // optimistic update
      await api.like(post.id);
    }

    Correct answer: Yes: it overrides the value until a dependency changes

    Overriding deriveds is handy for optimistic UI. Declare it with const if it must not be reassigned.

  3. 3. Which state does $effect track as dependencies?

    $effect(() => {
      console.log(color);
      setTimeout(() => console.log(size), 0);
    });

    Correct answer: Only values read synchronously inside: color, not size

    Values read after await or in callbacks aren't tracked. Dependencies are also re-collected on each run, so conditional reads matter.

  4. 4. Why is this an anti-pattern?

    let first = $state("Ann");
    let last = $state("Lee");
    let full = $state("");
    
    $effect(() => {
      full = first + " " + last;
    });

    Correct answer: It syncs state in an effect; $derived is the right tool

    Effects are an escape hatch for side effects. If a value can be computed from state, it should be derived.

  5. 5. How do you read state inside $effect without making it a dependency?

    import { untrack } from "svelte";
    
    $effect(() => {
      save(data, untrack(() => settings.format));
    });

    Correct answer: Wrap the read in untrack(() => ...)

    The effect re-runs when data changes but not when settings.format changes.

  6. 6. What is the difference between $effect and $effect.pre?

    Correct answer: $effect.pre runs before DOM updates, $effect after

    $effect.pre replaces beforeUpdate from Svelte 4, and $effect replaces afterUpdate.

  7. 7. When is $state.raw a good choice?

    let rows = $state.raw([]);
    rows = await fetchRows(); // reassign, don't push

    Correct answer: For large data that is replaced as a whole

    Raw state isn't deeply reactive: rows.push(x) won't trigger updates, only reassignment does.

  8. 8. How do you make class fields reactive?

    class Todo {
      text = $state("");
      done = $state(false);
      toggle = () => { this.done = !this.done; };
    }

    Correct answer: Declare the fields with $state

    Class instances aren't proxied. The compiler turns $state fields into getters/setters. An arrow function keeps this correct when used as an event handler.

  9. 9. Why doesn't items.set(k, v) update the UI when items is a plain Map in $state?

    Correct answer: $state doesn't proxy a Map; use SvelteMap

    svelte/reactivity also has SvelteSet, SvelteDate, SvelteURL, SvelteURLSearchParams and MediaQuery. Their values aren't made deeply reactive.

  10. 10. What does $props() give you besides named props?

    let { variant = "primary", children, ...rest } = $props();

    Correct answer: Rest props that you can spread onto an element

    This replaces $$props and $$restProps from Svelte 4. Event handlers like onclick are just props too.

  11. 11. Why does color not update when the type prop changes?

    let { type } = $props();
    let color = type === "danger" ? "red" : "green";

    Correct answer: It's computed once at creation; use $derived

    Treat props as values that can change: anything computed from them should be derived.

  12. 12. What does $inspect.trace() help with?

    Correct answer: It logs which dependency triggered the re-run

    Useful when something updates too often or not at all. Like $inspect, it does nothing in production.

  13. 13. How do you write reusable reactive logic (like a hook) in Svelte 5?

    // counter.svelte.js
    export function createCounter() {
      let count = $state(0);
      return {
        get count() { return count; },
        increment: () => count++,
      };
    }

    Correct answer: A function in a .svelte.js file that uses runes

    Returning count directly would give a snapshot of the number; a getter keeps reads reactive.

  14. 14. How do you pass named content areas (formerly named slots) to a component?

    <Table data={rows}>
      {#snippet header()}
        <th>Name</th>
      {/snippet}
      {#snippet row(item)}
        <td>{item.name}</td>
      {/snippet}
    </Table>

    Correct answer: Declare snippets inside the component's tags

    Inside Table they are received with $props() and rendered with {@render header()} and {@render row(item)}.

  15. 15. What is an advantage of snippets over Svelte 4 slots?

    Correct answer: They are values: you can pass, type and reuse them

    Top-level snippets can even be referenced inside <script>, and exported from <script module> if they don't use component state.

  16. 16. What is an attachment ({@attach})?

    <script>
      function autofocus(node) {
        node.focus();
      }
    </script>
    
    <input {@attach autofocus} />

    Correct answer: A function that runs in an effect when the element mounts

    Added in Svelte 5.29 as a more flexible replacement for use: actions. Attachments can also be passed through components via spread props.

  17. 17. Why are attachments more flexible than actions?

    Correct answer: They re-run when reactive values change and can be passed to components

    Library actions can be converted with fromAction from svelte/attachments.

  18. 18. What does a function binding do (Svelte 5.9+)?

    <input bind:value={
      () => value,
      (v) => value = v.toLowerCase()
    } />

    Correct answer: It controls reads and writes with a getter and a setter

    Before function bindings you'd need a separate oninput handler or an effect to transform values.

  19. 19. Which bindings are read-only?

    Correct answer: Dimension bindings like bind:clientWidth

    They are measured with a ResizeObserver, so you can read them but assigning has no effect.

  20. 20. Why are transitions in Svelte local by default?

    {#if showList}
      {#each items as item}
        <li transition:slide>{item}</li>
      {/each}
    {/if}

    Correct answer: They play only when their own block changes, not a parent's

    So toggling showList won't animate each item, but adding an item to items will.

  21. 21. What is Tween / Spring in svelte/motion used for?

    Correct answer: Smoothly animating numeric values over time

    Set .target and read .current, which moves toward the target with an easing or a spring.

  22. 22. How do you make context reactive?

    <script>
      import { setContext } from "svelte";
      let user = $state({ name: "Ann" });
      setContext("user", user);
    </script>

    Correct answer: Pass a $state object and mutate it

    Reassigning the variable user = {...} doesn't update context, because the context holds the original object.

  23. 23. What does createContext (Svelte 5.40+) give you?

    import { createContext } from "svelte";
    export const [getUser, setUser] = createContext<User>();

    Correct answer: A typed pair of functions to get and set context

    getUser() throws if no ancestor set the context, which catches mistakes early. Svelte recommends it over setContext/getContext.

  24. 24. Why is module-level shared state risky in a SvelteKit app?

    // state.svelte.js
    export const cart = $state({ items: [] });

    Correct answer: On the server all requests share it, so user data can leak

    Keep per-user state in context created within the component tree, or in the URL, and persist real data in a database.

  25. 25. When do stores still make sense in Svelte 5?

    Correct answer: For complex async streams, for example with RxJS

    For most cross-component state, $state in .svelte.js modules or classes is simpler.

  26. 26. What does derived from svelte/store do?

    const total = derived([price, qty], ([$price, $qty]) => $price * $qty);

    Correct answer: Creates a store computed from other stores

    The callback can also take set to produce values asynchronously.

  27. 27. How do you mount a Svelte 5 component into the page manually?

    import { mount } from "svelte";
    import App from "./App.svelte";
    
    const app = mount(App, { target: document.getElementById("app"), props: { name: "Ann" } });

    Correct answer: With mount(Component, { target, props })

    new Component() was the Svelte 4 API. For server-rendered HTML use hydrate instead of mount.

  28. 28. What does flushSync() from svelte do?

    Correct answer: Synchronously applies pending state changes to the DOM

    Svelte batches updates in a microtask. await tick() is the async alternative.

  29. 29. How are Svelte components usually unit-tested?

    Correct answer: With Vitest and @testing-library/svelte

    Logic with runes in .svelte.js files can be tested in .svelte.test.js files, where runes are compiled.

  30. 30. How do you test an effect created outside a component?

    const cleanup = $effect.root(() => {
      $effect(() => log.push(count));
    });
    // ...
    cleanup();

    Correct answer: Wrap it in $effect.root and clean up manually

    $effect must run inside a parent effect or component. $effect.root provides that context in tests and long-lived logic.

  31. 31. How do you build a Svelte component as a custom element?

    <svelte:options customElement="my-counter" />

    Correct answer: Set customElement in <svelte:options> and the compiler

    Inside, $host() gives access to the host element, e.g. to dispatch events.

  32. 32. When does a universal load in +page.js run?

    Correct answer: On the server first, then in the browser on navigation

    So it can't use secrets or database clients; that belongs in +page.server.js.

  33. 33. What must data returned from a server load be?

    Correct answer: Serializable with devalue, since it's sent to the browser

    A universal load can return non-serializable values (like a component), because it runs in the browser too.

  34. 34. Why use the fetch passed to load instead of the global one?

    Correct answer: It forwards cookies and inlines responses for hydration

    Requests to your own +server.js endpoints during SSR even call the handler directly without HTTP.

  35. 35. How does a page load get data from its layout's load?

    export async function load({ parent }) {
      const { user } = await parent();
      return { posts: await getPosts(user.id) };
    }

    Correct answer: With await parent()

    Call parent() after starting independent work, otherwise you create a waterfall.

  36. 36. How do you validate a form in a SvelteKit action and return errors?

    import { fail } from "@sveltejs/kit";
    
    export const actions = {
      default: async ({ request }) => {
        const data = await request.formData();
        const email = data.get("email");
        if (!email) return fail(400, { email, missing: true });
        // ...
      },
    };

    Correct answer: Return fail(status, data) from the action

    Returning the submitted values lets the form keep what the user typed.

  37. 37. How do you call a named action from a form?

    <form method="POST" action="?/login">...</form>

    Correct answer: Set action="?/login" on the form

    A button can override it with formaction="?/register". A page can't have both a default and named actions.

  38. 38. What does use:enhance add to a form?

    Correct answer: Submission through fetch, without a full page reload

    Without JavaScript the form still works as a regular POST. The behaviour can be customized with a submit function.

  39. 39. What is handle in hooks.server.js used for?

    export async function handle({ event, resolve }) {
      event.locals.user = await getUser(event.cookies.get("session"));
      return resolve(event);
    }

    Correct answer: Running code for every server request

    event.locals is then available in server load functions, actions and endpoints for that request.

  40. 40. How do you redirect from a server load or action?

    import { redirect } from "@sveltejs/kit";
    
    if (!locals.user) redirect(303, "/login");

    Correct answer: Call redirect(status, location)

    Use 303 after a POST so the browser follows with GET. Don't call redirect inside a try block that swallows it.

  41. 41. What do the page options ssr = false and csr = false do?

    Correct answer: ssr = false renders in the browser only; csr = false sends no client JS

    Turning off SSR hurts SEO and first paint; turning off CSR removes interactivity and client navigation.

  42. 42. What does a route group like src/routes/(marketing)/about do?

    Correct answer: Shares a layout without changing the URL

    Groups let different sections have different layouts while keeping clean URLs.

  43. 43. What does data-sveltekit-preload-data="hover" do?

    Correct answer: Loads a link's code and data when the user hovers it

    The default template sets it on <body>, so all links benefit. "tap" preloads only on press.

  44. 44. How do you make a module server-only in SvelteKit?

    Correct answer: Add .server to the file name, like db.server.js

    This prevents secrets and database clients from ending up in the browser bundle, even through indirect imports.

  45. 45. What are beforeNavigate and afterNavigate used for?

    Correct answer: Running code around client-side navigation

    beforeNavigate can cancel navigation. onNavigate is handy for the View Transitions API.

  46. 46. What does export const snapshot in +page.svelte allow?

    export const snapshot = {
      capture: () => comment,
      restore: (value) => (comment = value),
    };

    Correct answer: Restoring temporary UI state when the user comes back

    The value is stored in sessionStorage, so it must be JSON-serializable and small.

  47. 47. How do you build a fully static site with SvelteKit?

    Correct answer: Use adapter-static and prerender all pages

    Pages that need request-time data can't be prerendered; for a pure SPA use a fallback page instead.

  48. 48. What does this code show after clicking the button?

    <script>
      let todos = $state([{ text: "A", done: false }]);
      const first = todos[0];
    </script>
    
    <button onclick={() => (first.done = true)}>Done</button>
    <p>{todos[0].done}</p>

    Correct answer: true: first is the same proxy as todos[0]

    Reading an object property from a deep state proxy returns a proxy too. Destructuring primitives, however, loses reactivity.

  49. 49. Why isn't count reactive in the importing component?

    // counter.svelte.js
    export let count = $state(0);
    export function increment() { count += 1; }

    Correct answer: Reassigned state can't be exported; export an object

    Svelte reports a compile error for this pattern. export const counter = $state({ count: 0 }) works because you mutate a property.

  50. 50. How do you show a loading indicator during SvelteKit navigation?

    <script>
      import { navigating } from "$app/state";
    </script>
    
    {#if navigating.to}<ProgressBar />{/if}

    Correct answer: Read navigating from $app/state

    navigating has from, to and type. On the server its values are null.

  51. 51. What is MediaQuery from svelte/reactivity?

    const large = new MediaQuery("min-width: 800px");

    Correct answer: A reactive wrapper with a current match flag

    On the server the value can't be known, which may cause content changes on hydration; prefer CSS media queries when possible.

  52. 52. How can a component expose methods to its parent?

    <!-- Dialog.svelte -->
    <script>
      let dialog;
      export function open() { dialog.showModal(); }
    </script>
    <dialog bind:this={dialog}>...</dialog>
    
    <!-- Parent -->
    <Dialog bind:this={d} />
    <button onclick={() => d.open()}>Open</button>

    Correct answer: Export a function, then call it via bind:this

    Exported functions and constants become the component's instance API. Prefer props for data flow and keep this for imperative actions.

  53. 53. What does <script module> do?

    Correct answer: Its code runs once per module, shared by all instances

    In Svelte 4 this was <script context="module">. Use it for shared constants, helpers or exported snippets.

  54. 54. Which statement about {#each} with destructuring is correct?

    {#each items as { name, qty } (name)}
      <input bind:value={qty} />
    {/each}

    Correct answer: Binding to a destructured value doesn't update the item

    Svelte's best practices advise avoiding destructuring when you need to mutate the item.

  55. 55. What is the purpose of +page.server.js returning a promise for slow data?

    export async function load() {
      return {
        post: await getPost(),
        comments: getComments(), // not awaited
      };
    }

    Correct answer: The page shows post at once, and comments stream in later

    Streaming improves time to first content. On platforms without streaming support, the response waits for everything.

  56. 56. What is wrong with this $effect?

    $effect(() => {
      if (browser) {
        window.addEventListener("resize", onResize);
      }
    });

    Correct answer: The browser check is redundant and cleanup is missing

    <svelte:window> adds and removes the listener for you. If you do use an effect, return a function that removes the listener.

  57. 57. What does a +error.svelte page show?

    Correct answer: The nearest error page for load and render errors

    For errors in the root layout or handle, SvelteKit uses the static src/error.html fallback.

  58. 58. What does $props.id() (Svelte 5.20+) generate?

    <script>
      const uid = $props.id();
    </script>
    
    <label for="{uid}-email">Email</label>
    <input id="{uid}-email" />

    Correct answer: An instance id that matches in SSR and hydration

    Random ids generated with Math.random() would differ between server and client and break hydration.

  59. 59. How do you give a $bindable prop a fallback value?

    let { open = $bindable(false) } = $props();

    Correct answer: Pass the fallback as an argument to $bindable(...)

    If the parent does bind it, the component writes changes back to the parent's state.

  60. 60. How do you render fallback content when no children snippet was passed?

    {#if children}
      {@render children()}
    {:else}
      <p>Nothing here</p>
    {/if}

    Correct answer: Check the prop in {#if} and use {:else}

    Snippet props are just values that may be undefined; for a simple render without fallback use {@render children?.()}.

  61. 61. How do you listen to visibilitychange on document in a component?

    Correct answer: <svelte:document onvisibilitychange={handler} />

    <svelte:body> similarly handles events like mouseenter on document.body. Svelte removes the listeners on destroy.

  62. 62. How do you pass parameters to a transition?

    <div in:fly={{ y: 20, duration: 300 }} out:fade>...</div>

    Correct answer: in:fly={{ y: 20, duration: 300 }}

    Common parameters are delay, duration and easing (functions from svelte/easing).

  63. 63. How does in:/out: differ from transition:?

    Correct answer: transition: can reverse mid-way; in: and out: are independent

    If an element is toggled while its outro is playing, transition: reverses smoothly, whereas in: starts its own animation alongside.

  64. 64. Can <select bind:value> hold objects, not just strings?

    <select bind:value={selected}>
      {#each users as user}
        <option value={user}>{user.name}</option>
      {/each}
    </select>

    Correct answer: Yes: selected gets the object itself

    With <select multiple> the bound value is an array.

  65. 65. How do you read a store's current value once, outside a component?

    import { get } from "svelte/store";
    const value = get(count);

    Correct answer: With get(store) from svelte/store

    The $ prefix works only in components. get is fine for occasional reads; avoid it in hot paths.

  66. 66. What does the second argument of readable do?

    const time = readable(new Date(), (set) => {
      const id = setInterval(() => set(new Date()), 1000);
      return () => clearInterval(id);
    });

    Correct answer: A start function called for the first subscriber

    This lazy setup and cleanup makes stores efficient wrappers for external sources.

  67. 67. How do you check whether a context exists before reading it?

    Correct answer: With hasContext(key) from svelte

    getContext returns undefined for a missing key; getAllContexts returns the whole map, e.g. to pass it to mount.

  68. 68. What happens when export const ssr = false is set in a +layout.js?

    Correct answer: It applies to all child pages of that layout

    Page options cascade from layouts to children, which makes it easy to configure whole sections.

  69. 69. How do you set cache headers for a page from load?

    export async function load({ fetch, setHeaders }) {
      const res = await fetch("/api/products");
      setHeaders({ "cache-control": res.headers.get("cache-control") });
      return { products: await res.json() };
    }

    Correct answer: Call setHeaders inside load

    Each header can be set only once. setHeaders has no effect when load runs in the browser.

  70. 70. How do you read and set cookies on the server in SvelteKit?

    Correct answer: With cookies.get and cookies.set from the event

    SvelteKit sets secure defaults for httpOnly, secure and path, which you can override.

  71. 71. What does a param matcher like [id=integer] do?

    Correct answer: Matches only if a matcher function accepts the segment

    If the matcher rejects the value, SvelteKit tries other routes, which is useful to disambiguate similar paths.

  72. 72. What is the rest parameter [...path] useful for?

    Correct answer: Matching any number of URL segments

    A [...rest] route in a folder can render a custom not-found page for that section.

  73. 73. What happens if both +page.js and +page.server.js export load?

    Correct answer: The server load runs first and feeds the universal one

    This lets you fetch on the server and then add non-serializable things, like a component, in the universal load.

  74. 74. How do you test a component that expects snippet props?

    Correct answer: Use createRawSnippet or a small wrapper component

    A wrapper component in the test folder keeps the test close to how real users of the component pass content.

  75. 75. What does untrack NOT do?

    Correct answer: It doesn't make the value non-reactive everywhere

    Other effects that read the same state directly still re-run when it changes.