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. When should you use
$derived.byinstead 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. Can you assign to a
$derivedvalue (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
constif it must not be reassigned.3. Which state does
$effecttrack as dependencies?$effect(() => { console.log(color); setTimeout(() => console.log(size), 0); });Correct answer: Only values read synchronously inside:
color, notsizeValues read after
awaitor in callbacks aren't tracked. Dependencies are also re-collected on each run, so conditional reads matter.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;
$derivedis the right toolEffects are an escape hatch for side effects. If a value can be computed from state, it should be derived.
5. How do you read state inside
$effectwithout 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
datachanges but not whensettings.formatchanges.6. What is the difference between
$effectand$effect.pre?Correct answer:
$effect.preruns before DOM updates,$effectafter$effect.prereplacesbeforeUpdatefrom Svelte 4, and$effectreplacesafterUpdate.7. When is
$state.rawa good choice?let rows = $state.raw([]); rows = await fetchRows(); // reassign, don't pushCorrect 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. 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
$stateClass instances aren't proxied. The compiler turns
$statefields into getters/setters. An arrow function keepsthiscorrect when used as an event handler.9. Why doesn't
items.set(k, v)update the UI whenitemsis a plainMapin$state?Correct answer:
$statedoesn't proxy aMap; useSvelteMapsvelte/reactivityalso hasSvelteSet,SvelteDate,SvelteURL,SvelteURLSearchParamsandMediaQuery. Their values aren't made deeply reactive.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
$$propsand$$restPropsfrom Svelte 4. Event handlers likeonclickare just props too.11. Why does
colornot update when thetypeprop changes?let { type } = $props(); let color = type === "danger" ? "red" : "green";Correct answer: It's computed once at creation; use
$derivedTreat props as values that can change: anything computed from them should be derived.
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. 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.jsfile that uses runesReturning
countdirectly would give a snapshot of the number; a getter keeps reads reactive.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
Tablethey are received with$props()and rendered with{@render header()}and{@render row(item)}.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. 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. 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
fromActionfromsvelte/attachments.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
oninputhandler or an effect to transform values.19. Which bindings are read-only?
Correct answer: Dimension bindings like
bind:clientWidthThey are measured with a
ResizeObserver, so you can read them but assigning has no effect.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
showListwon't animate each item, but adding an item toitemswill.21. What is
Tween/Springinsvelte/motionused for?Correct answer: Smoothly animating numeric values over time
Set
.targetand read.current, which moves toward the target with an easing or a spring.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
$stateobject and mutate itReassigning the variable
user = {...}doesn't update context, because the context holds the original object.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 oversetContext/getContext.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. When do stores still make sense in Svelte 5?
Correct answer: For complex async streams, for example with RxJS
For most cross-component state,
$statein.svelte.jsmodules or classes is simpler.26. What does
derivedfromsvelte/storedo?const total = derived([price, qty], ([$price, $qty]) => $price * $qty);Correct answer: Creates a store computed from other stores
The callback can also take
setto produce values asynchronously.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 usehydrateinstead ofmount.28. What does
flushSync()fromsveltedo?Correct answer: Synchronously applies pending state changes to the DOM
Svelte batches updates in a microtask.
await tick()is the async alternative.29. How are Svelte components usually unit-tested?
Correct answer: With Vitest and
@testing-library/svelteLogic with runes in
.svelte.jsfiles can be tested in.svelte.test.jsfiles, where runes are compiled.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.rootand clean up manually$effectmust run inside a parent effect or component.$effect.rootprovides that context in tests and long-lived logic.31. How do you build a Svelte component as a custom element?
<svelte:options customElement="my-counter" />Correct answer: Set
customElementin<svelte:options>and the compilerInside,
$host()gives access to the host element, e.g. to dispatch events.32. When does a universal
loadin+page.jsrun?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. What must data returned from a server
loadbe?Correct answer: Serializable with devalue, since it's sent to the browser
A universal
loadcan return non-serializable values (like a component), because it runs in the browser too.34. Why use the
fetchpassed toloadinstead of the global one?Correct answer: It forwards cookies and inlines responses for hydration
Requests to your own
+server.jsendpoints during SSR even call the handler directly without HTTP.35. How does a page
loadget data from its layout'sload?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. 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 actionReturning the submitted values lets the form keep what the user typed.
37. How do you call a named action from a form?
<form method="POST" action="?/login">...</form>Correct answer: Set
action="?/login"on the formA button can override it with
formaction="?/register". A page can't have both adefaultand named actions.38. What does
use:enhanceadd 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. What is
handleinhooks.server.jsused 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.localsis then available in serverloadfunctions, actions and endpoints for that request.40. How do you redirect from a server
loador 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
redirectinside atryblock that swallows it.41. What do the page options
ssr = falseandcsr = falsedo?Correct answer:
ssr = falserenders in the browser only;csr = falsesends no client JSTurning off SSR hurts SEO and first paint; turning off CSR removes interactivity and client navigation.
42. What does a route group like
src/routes/(marketing)/aboutdo?Correct answer: Shares a layout without changing the URL
Groups let different sections have different layouts while keeping clean URLs.
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. How do you make a module server-only in SvelteKit?
Correct answer: Add
.serverto the file name, likedb.server.jsThis prevents secrets and database clients from ending up in the browser bundle, even through indirect imports.
45. What are
beforeNavigateandafterNavigateused for?Correct answer: Running code around client-side navigation
beforeNavigatecan cancel navigation.onNavigateis handy for the View Transitions API.46. What does
export const snapshotin+page.svelteallow?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. How do you build a fully static site with SvelteKit?
Correct answer: Use
adapter-staticand prerender all pagesPages that need request-time data can't be prerendered; for a pure SPA use a fallback page instead.
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:firstis the same proxy astodos[0]Reading an object property from a deep state proxy returns a proxy too. Destructuring primitives, however, loses reactivity.
49. Why isn't
countreactive 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. 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
navigatingfrom$app/statenavigatinghasfrom,toandtype. On the server its values arenull.51. What is
MediaQueryfromsvelte/reactivity?const large = new MediaQuery("min-width: 800px");Correct answer: A reactive wrapper with a
currentmatch flagOn the server the value can't be known, which may cause content changes on hydration; prefer CSS media queries when possible.
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:thisExported functions and constants become the component's instance API. Prefer props for data flow and keep this for imperative actions.
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. 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. What is the purpose of
+page.server.jsreturning a promise for slow data?export async function load() { return { post: await getPost(), comments: getComments(), // not awaited }; }Correct answer: The page shows
postat once, andcommentsstream in laterStreaming improves time to first content. On platforms without streaming support, the response waits for everything.
56. What is wrong with this
$effect?$effect(() => { if (browser) { window.addEventListener("resize", onResize); } });Correct answer: The
browsercheck 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. What does a
+error.sveltepage show?Correct answer: The nearest error page for
loadand render errorsFor errors in the root layout or
handle, SvelteKit uses the staticsrc/error.htmlfallback.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. How do you give a
$bindableprop 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. How do you render fallback content when no
childrensnippet 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. How do you listen to
visibilitychangeondocumentin a component?Correct answer:
<svelte:document onvisibilitychange={handler} /><svelte:body>similarly handles events likemouseenterondocument.body. Svelte removes the listeners on destroy.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,durationandeasing(functions fromsvelte/easing).63. How does
in:/out:differ fromtransition:?Correct answer:
transition:can reverse mid-way;in:andout:are independentIf an element is toggled while its outro is playing,
transition:reverses smoothly, whereasin:starts its own animation alongside.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:
selectedgets the object itselfWith
<select multiple>the bound value is an array.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)fromsvelte/storeThe
$prefix works only in components.getis fine for occasional reads; avoid it in hot paths.66. What does the second argument of
readabledo?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. How do you check whether a context exists before reading it?
Correct answer: With
hasContext(key)fromsveltegetContextreturnsundefinedfor a missing key;getAllContextsreturns the whole map, e.g. to pass it tomount.68. What happens when
export const ssr = falseis 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. 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
setHeadersinsideloadEach header can be set only once.
setHeadershas no effect whenloadruns in the browser.70. How do you read and set cookies on the server in SvelteKit?
Correct answer: With
cookies.getandcookies.setfrom the eventSvelteKit sets secure defaults for
httpOnly,secureandpath, which you can override.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. What is the
restparameter[...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. What happens if both
+page.jsand+page.server.jsexportload?Correct answer: The server
loadruns first and feeds the universal oneThis lets you fetch on the server and then add non-serializable things, like a component, in the universal load.
74. How do you test a component that expects snippet props?
Correct answer: Use
createRawSnippetor a small wrapper componentA wrapper component in the test folder keeps the test close to how real users of the component pass content.
75. What does
untrackNOT 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.