
Svelte's unique compile-time approach and reactive programming model make it a powerful framework for modern web development. Stark.ai offers a comprehensive collection of Svelte interview questions, real-world scenarios, and expert guidance to help you excel in your next technical interview.
Svelte is a compiler that creates reactive JavaScript modules. Unlike React or Vue that do most of their work in the...
A Svelte component is created in a .svelte file with three main sections: <script> for JavaScript logic, <style> for...
Reactive variables in Svelte are declared using the let keyword in the <script> section. Any variables used in the...
The $ prefix in Svelte is a special syntax that marks a statement as reactive. It automatically re-runs the code...
Svelte uses #if, :else if, and :else blocks for conditional rendering. Example: {#if condition}...{:else if...
Svelte uses the #each block for iteration. Syntax: {#each items as item, index}...{/each}. Supports destructuring,...
The export keyword in Svelte is used to declare props that a component can receive. Example: export let name; Makes...
Events in Svelte are handled using the on: directive. Example: <button on:click={handleClick}>. Supports modifiers...
Component composition in Svelte involves building larger components from smaller ones. Components can be imported...
Styles are added in the <style> block and are automatically scoped to the component. Global styles can be added...
Reactivity in Svelte is the automatic updating of the DOM when data changes. It's handled through assignments to...
Writable stores are created using writable() from svelte/store. Example: const count = writable(0). Provides methods...
Reactive declarations use the $: syntax to automatically recompute values when dependencies change. Example: $:...
Arrays must be updated using assignment for reactivity. Use methods like [...array, newItem] for additions,...
Writable stores can be modified using set() and update(), while readable stores are read-only. Readable stores are...
Stores can be subscribed to using subscribe() method or automatically in templates using $ prefix. Example: $store...
Auto-subscription happens when using $ prefix with stores in components. Svelte automatically handles subscribe and...
Derived values can be created using reactive declarations ($:) or derived stores. They automatically update when...
The set function directly sets a new value for a writable store. Example: count.set(10). Triggers store updates and...
Objects must be updated through assignment for reactivity. Use spread operator or Object.assign for updates....
Props are declared using the export keyword in the script section. Example: export let propName. Optional props can...
Props are passed to child components as attributes in the markup. Example: <ChildComponent propName={value} />. Can...
Spread props allow passing multiple props using spread syntax. Example: <Component {...props} />. Useful when...
Prop validation can be handled through TypeScript types or runtime checks. Use if statements or assertions in...
Components dispatch custom events using createEventDispatcher. Parent listens using on:eventName. Example:...
Event forwarding passes events up through components using on:eventName. Component can forward DOM events or custom...
Two-way binding on props uses bind:propName. Example: <Input bind:value={name} />. Component must export the prop....
Reactive statements ($:) respond to prop changes. Can trigger side effects or derive values. Example: $:...
HTML attributes can be forwarded using $$props or $$restProps. Useful for wrapper components. Example: <div...
Props can be destructured in export statement. Example: export let { name, age } = data. Supports default values and...
Lifecycle methods in Svelte are functions that execute at different stages of a component's existence. Main...
onMount is a lifecycle function that runs after the component is first rendered to the DOM. It's commonly used for...
onDestroy is called when a component is unmounted from the DOM. Used for cleanup like unsubscribing from stores,...
beforeUpdate runs before the DOM is updated with new values. Useful for capturing pre-update state, like scroll...
afterUpdate runs after the DOM is updated with new values. Used for operations that require updated DOM state, like...
Async operations in onMount use async/await or promises. Handle loading states and errors appropriately. Example:...
Lifecycle methods execute in order: 1. Component creation, 2. beforeUpdate, 3. onMount, 4. afterUpdate. onDestroy...
Resource cleanup is done in onDestroy or by returning cleanup function from onMount. Clear intervals, timeouts,...
Svelte guarantees that onMount runs after DOM is ready, onDestroy runs before unmount, beforeUpdate before DOM...
During SSR, onMount and afterUpdate don't run. Other lifecycle methods run normally. Client-side hydration triggers...
DOM events in Svelte are handled using the on: directive. Example: <button on:click={handleClick}>. Supports all...
Event modifiers customize event behavior using | symbol. Common modifiers include preventDefault, stopPropagation,...
Custom events are created using createEventDispatcher. Import from svelte, initialize in component, then dispatch...
Component events are listened to using on:eventName. Parent components can listen to dispatched events. Example:...
Event forwarding passes events up through components using on:eventName. No handler needed for forwarding. Example:...
Inline handlers can be defined directly in the on: directive. Example: <button on:click={() => count += 1}>. Good...
Event delegation handles events at a higher level using bubbling. Attach single handler to parent for multiple...
Data is passed as second argument to dispatch. Example: dispatch('custom', { detail: value }). Accessed in handler...
Event object contains event details passed to handlers. Includes properties like target, currentTarget,...
Multiple events use multiple on: directives. Example: <div on:click={handleClick} on:mouseover={handleHover}>. Each...
Stores in Svelte are reactive data containers that can be shared across components. They provide a way to manage...
Writable stores are created using writable() from svelte/store. Example: const count = writable(0). They provide...
The store contract requires an object with subscribe method that takes a callback and returns unsubscribe function....
Store changes can be subscribed to using subscribe method or $ prefix in components. Example: count.subscribe(value...
Readable stores are created using readable() and are read-only. They can only be updated through their start...
Derived stores are created using derived() and compute values based on other stores. Example: const doubled =...
Auto-subscription happens when using $ prefix with stores in components. Svelte automatically handles subscribe and...
Store values can be updated using set() or update() methods. Example: count.set(10) or count.update(n => n + 1)....
Stores are initialized with initial value in creation. Example: writable(initialValue). Can be undefined. Support...
Stores integrate with Svelte's reactivity system. Changes trigger reactive updates. Work with reactive declarations...
Transitions in Svelte are built-in animations that play when elements are added to or removed from the DOM. They are...
Fade transition is used with transition:fade directive. Example: <div transition:fade>. Can accept parameters like...
in: and out: directives specify different transitions for entering and leaving. Example: <div in:fade out:fly>....
Transition parameters customize animation behavior. Example: transition:fade={{duration: 300, delay: 100}}. Include...
Fly transition animates position and opacity. Example: <div transition:fly={{y: 200}}>. Parameters include x, y...
Slide transition animates element height. Example: <div transition:slide>. Useful for collapsible content. Can...
Easing functions define animation progression. Import from svelte/easing. Example: transition:fade={{easing:...
transition:local restricts transitions to when parent component is added/removed. Prevents transitions during...
Scale transition animates size and opacity. Example: <div transition:scale>. Parameters include start, opacity,...
Draw transition animates SVG paths. Example: <path transition:draw>. Parameters include duration, delay, easing....
Slots are placeholders in components that allow parent components to pass content. Defined using <slot> element....
Default slots provide fallback content. Example: <slot>Default content</slot>. Content appears when parent doesn't...
Named slots target specific slot locations using name attribute. Example: <slot name='header'>. Content provided...
Content is passed to named slots using slot attribute. Example: <div slot='header'>Header content</div>. Must match...
Slot props pass data from child to parent through slots. Use let:propertyName directive. Example: <slot name='item'...
Use $$slots object to check slot content. Example: {#if $$slots.header}. Available in component script and template....
Fallback content appears when slot is empty. Defined between slot tags. Example: <slot>Fallback</slot>. Provides...
Slots enable flexible component composition. Support content injection at multiple points. Allow component reuse...
Slot content maintains parent component scope. Can access parent variables and functions. Cannot directly access...
Slot content can be styled in both parent and child. Child styles using :slotted() selector. Parent styles apply...
Slots are placeholders in components that allow parent components to pass content. Defined using <slot> element....
Default slots provide fallback content. Example: <slot>Default content</slot>. Content appears when parent doesn't...
Content is passed to named slots using slot attribute. Example: <div slot='header'>Header content</div>. Must match...
Slot props pass data from child to parent through slots. Use let:propertyName directive. Example: <slot name='item'...
Use $$slots object to check slot content. Example: {#if $$slots.header}. Available in component script and template....
Fallback content appears when slot is empty. Defined between slot tags. Example: <slot>Fallback</slot>. Provides...
Slots enable flexible component composition. Support content injection at multiple points. Allow component reuse...
Slot content maintains parent component scope. Can access parent variables and functions. Cannot directly access...
Slot content can be styled in both parent and child. Child styles using :slotted() selector. Parent styles apply...
SvelteKit provides file-based routing where files in the routes directory automatically become pages. URLs...
Create a route by adding a +page.svelte file in the routes directory. Example: src/routes/about/+page.svelte becomes...
Dynamic routes use square brackets in file names. Example: [slug]/+page.svelte creates dynamic segment. Parameters...
Route parameters accessed through page.params. Example: export let data; const { slug } = data. Available in...
Layout files (+layout.svelte) provide shared UI for multiple routes. Define common elements like navigation, footer....
Navigation uses <a> tags or programmatic goto function. SvelteKit handles client-side navigation. Supports...
Route groups organize routes using (group) syntax. Don't affect URL structure. Share layouts within groups. Support...
Data loading uses +page.js or +page.server.js files. Export load function for data fetching. Returns props for page...
Error page (+error.svelte) handles route errors. Displays when errors occur. Access error details through error...
Redirects use redirect function from @sveltejs/kit. Can redirect in load functions or actions. Support...
The Context API allows passing data through the component tree without prop drilling. Uses setContext and getContext...
Context is set using setContext function from svelte. Example: setContext('key', value). Must be called during...
Context is retrieved using getContext function. Example: const value = getContext('key'). Must use same key as...
Context keys must be unique within component tree. Often use symbols for guaranteed uniqueness. Example: const key =...
Context exists throughout component lifecycle. Created during initialization. Available until component destruction....
Common uses include theme data, localization, authentication state, shared functionality. Useful for cross-cutting...
Functions can be shared through context. Example: setContext('api', { method: () => {} }). Allows child components...
Context is scoped to component and descendants. Not available to parent or sibling components. Multiple instances...
getContext returns undefined if context not found. Should handle undefined case. Can provide default values....
Context is static, set during initialization. Stores are reactive, can change over time. Context good for static...
Bindings create two-way data flow between DOM elements and variables using bind: directive. Example: <input...
Basic form bindings include value for text inputs, checked for checkboxes, group for radio/checkbox groups. Example:...
use: directive attaches actions (reusable DOM node functionality) to elements. Example: <div use:action>. Actions...
class: directive conditionally applies CSS classes. Example: <div class:active={isActive}>. Shorthand available when...
Custom component binding uses bind: on exported props. Component must export the variable. Example: <CustomInput...
style: directive sets inline styles conditionally. Example: <div style:color={textColor}>. Can use shorthand when...
Select elements bind using value or selectedIndex. Example: <select bind:value={selected}>. Supports multiple...
this binding references DOM element or component instance. Example: <div bind:this={element}>. Useful for direct DOM...
bind:group groups radio/checkbox inputs. Binds multiple inputs to single value/array. Example: <input type='radio'...
Contenteditable elements bind using textContent or innerHTML. Example: <div contenteditable...
Server-Side Rendering (SSR) generates HTML on the server instead of client. Provides better initial page load, SEO...
Hydration is the process where client-side JavaScript takes over server-rendered HTML. Makes static content...
Server-side data loading uses load functions in +page.server.js. Returns data for page rendering. Supports async...
Client-Side Rendering (CSR) fallback handles cases where SSR fails or is disabled. Uses +page.js instead of...
Disable SSR using export const ssr = false in +page.js. Page renders only on client. Useful for browser-specific...
Server-only modules run exclusively on server. Use .server.js extension. Cannot be imported by client code. Useful...
SSR errors handled by error.svelte pages. Support error boundaries. Can provide fallback content. Error details...
Streaming SSR sends HTML in chunks as it's generated. Improves Time To First Byte (TTFB). Supports progressive...
Environment variables accessed through $env/static/private or $env/dynamic/private. Only available server-side. Must...
Prerendering generates static HTML at build time. Uses export const prerender = true. Improves performance. Suitable...
Vitest is the recommended testing framework for Svelte applications. It's fast, provides good integration with...
Component tests use @testing-library/svelte. Mount components using render method. Test component behavior and DOM...
Svelte Inspector is a development tool enabled with 'ctrl + shift + i'. Shows component hierarchy, props, state....
Async tests use async/await syntax. Test async operations using act function. Handle promises and timeouts. Example:...
Testing matchers verify component state/behavior. Include toBeInTheDocument, toHaveTextContent, toBeVisible....
Store state can be debugged using $store syntax. Subscribe to store changes. Log state updates. Use Svelte devtools....
Testing hierarchy includes unit tests, integration tests, end-to-end tests. Focus on component isolation. Test...
Event handlers tested using fireEvent. Simulate user interactions. Verify event outcomes. Example:...
Snapshot testing captures component output. Compares against stored snapshots. Detects UI changes. Example:...
Props testing verifies component behavior with different props. Test prop types and values. Handle prop updates....
Svelte achieves performance through compile-time optimization. Generates vanilla JavaScript with minimal runtime...
Code splitting automatically breaks application into smaller chunks. Routes loaded on demand. Reduces initial bundle...
Svelte compiles reactive statements into efficient JavaScript. Updates only affected DOM elements. No diffing...
Asset optimization includes minification, bundling, compression. Uses Vite for build process. Optimizes images and...
Component optimization includes proper key usage, avoiding unnecessary updates, using tick() function. Implement...
Lazy loading defers loading of components until needed. Uses dynamic imports. Supports route-level code splitting....
Memory leak prevention includes proper cleanup in onDestroy, unsubscribing from stores, removing event listeners....
Prefetching loads route data before navigation. Uses sveltekit:prefetch directive. Improves perceived performance....
Store optimization includes batching updates, using derived stores efficiently, implementing selective updates....
Tree-shaking removes unused code during build. Reduces bundle size. Supported by default. Works with ES modules....
Svelte is a compiler that creates reactive JavaScript modules. Unlike React or Vue that do most of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app, resulting in highly optimized vanilla JavaScript with minimal runtime overhead.
A Svelte component is created in a .svelte file with three main sections: <script> for JavaScript logic, <style> for component-scoped CSS, and the template section for HTML markup. Styles are automatically scoped to the component.
Reactive variables in Svelte are declared using the let keyword in the <script> section. Any variables used in the template are automatically reactive. Example: let count = 0. When count changes, the UI automatically updates.
The $ prefix in Svelte is a special syntax that marks a statement as reactive. It automatically re-runs the code whenever any referenced values change. It's commonly used with derived values and store subscriptions.
Svelte uses #if, :else if, and :else blocks for conditional rendering. Example: {#if condition}...{:else if otherCondition}...{:else}...{/if}. These blocks can contain any valid HTML or component markup.
Svelte uses the #each block for iteration. Syntax: {#each items as item, index}...{/each}. Supports destructuring, key specification, and else blocks for empty arrays. Example: {#each users as {id, name} (id)}.
The export keyword in Svelte is used to declare props that a component can receive. Example: export let name; Makes the variable available as a prop when using the component: <Component name='value' />.
Events in Svelte are handled using the on: directive. Example: <button on:click={handleClick}>. Supports modifiers like preventDefault using |. Example: <form on:submit|preventDefault={handleSubmit}>.
Component composition in Svelte involves building larger components from smaller ones. Components can be imported and used like HTML elements. Example: import Child from './Child.svelte'; then use <Child /> in template.
Styles are added in the <style> block and are automatically scoped to the component. Global styles can be added using :global() modifier. Supports regular CSS with automatic vendor prefixing.
Reactivity in Svelte is the automatic updating of the DOM when data changes. It's handled through assignments to declared variables and the $: syntax. Svelte's compiler creates the necessary code to update the DOM when dependencies change.
Writable stores are created using writable() from svelte/store. Example: const count = writable(0). Provides methods like set() and update() to modify the store value. Subscribe to changes using subscribe() method.
Reactive declarations use the $: syntax to automatically recompute values when dependencies change. Example: $: doubled = count * 2. They run whenever any referenced values change.
Arrays must be updated using assignment for reactivity. Use methods like [...array, newItem] for additions, array.filter() for removals, or array.map() for updates. Assignment triggers reactivity.
Writable stores can be modified using set() and update(), while readable stores are read-only. Readable stores are created using readable() and only change through their start function.
Stores can be subscribed to using subscribe() method or automatically in templates using $ prefix. Example: $store in template or store.subscribe(value => {}) in script.
Auto-subscription happens when using $ prefix with stores in components. Svelte automatically handles subscribe and unsubscribe. No manual cleanup needed. Works in template and reactive statements.
Derived values can be created using reactive declarations ($:) or derived stores. They automatically update when dependencies change. Used for computed values that depend on other state.
The set function directly sets a new value for a writable store. Example: count.set(10). Triggers store updates and notifies all subscribers. Used for direct value updates.
Objects must be updated through assignment for reactivity. Use spread operator or Object.assign for updates. Example: obj = {...obj, newProp: value}. Assignment triggers reactivity.
Props are declared using the export keyword in the script section. Example: export let propName. Optional props can have default values: export let propName = defaultValue. Props are passed to components as attributes.
Props are passed to child components as attributes in the markup. Example: <ChildComponent propName={value} />. Can use shorthand when prop name matches variable: <ChildComponent {value} />.
Spread props allow passing multiple props using spread syntax. Example: <Component {...props} />. Useful when forwarding many props. All properties of the object become individual props.
Prop validation can be handled through TypeScript types or runtime checks. Use if statements or assertions in component initialization. Can throw errors for invalid props.
Components dispatch custom events using createEventDispatcher. Parent listens using on:eventName. Example: dispatch('message', data). Events bubble by default.
Event forwarding passes events up through components using on:eventName. Component can forward DOM events or custom events. Use on:message|stopPropagation to prevent bubbling.
Two-way binding on props uses bind:propName. Example: <Input bind:value={name} />. Component must export the prop. Updates flow both ways between parent and child.
Reactive statements ($:) respond to prop changes. Can trigger side effects or derive values. Example: $: console.log(propName). Runs whenever referenced props update.
HTML attributes can be forwarded using $$props or $$restProps. Useful for wrapper components. Example: <div {...$$restProps}>. Passes any unhandled props to element.
Props can be destructured in export statement. Example: export let { name, age } = data. Supports default values and renaming. Makes prop handling more concise.
Lifecycle methods in Svelte are functions that execute at different stages of a component's existence. Main lifecycle methods include onMount, onDestroy, beforeUpdate, and afterUpdate. They help manage side effects and component behavior.
onMount is a lifecycle function that runs after the component is first rendered to the DOM. It's commonly used for initialization, data fetching, and setting up subscriptions. Returns a cleanup function optionally.
onDestroy is called when a component is unmounted from the DOM. Used for cleanup like unsubscribing from stores, clearing intervals, or removing event listeners. Prevents memory leaks.
beforeUpdate runs before the DOM is updated with new values. Useful for capturing pre-update state, like scroll position. Can be used multiple times in a component.
afterUpdate runs after the DOM is updated with new values. Used for operations that require updated DOM state, like updating scroll position or third-party libraries.
Async operations in onMount use async/await or promises. Handle loading states and errors appropriately. Example: onMount(async () => { const data = await fetchData(); })
Lifecycle methods execute in order: 1. Component creation, 2. beforeUpdate, 3. onMount, 4. afterUpdate. onDestroy runs when component is unmounted. Updates trigger beforeUpdate and afterUpdate.
Resource cleanup is done in onDestroy or by returning cleanup function from onMount. Clear intervals, timeouts, event listeners, and subscriptions to prevent memory leaks.
Svelte guarantees that onMount runs after DOM is ready, onDestroy runs before unmount, beforeUpdate before DOM updates, and afterUpdate after DOM updates. Component initialization always runs.
During SSR, onMount and afterUpdate don't run. Other lifecycle methods run normally. Client-side hydration triggers lifecycle methods appropriately. Handle SSR-specific logic.
DOM events in Svelte are handled using the on: directive. Example: <button on:click={handleClick}>. Supports all standard DOM events like click, submit, input, etc. Event handler receives the event object as parameter.
Event modifiers customize event behavior using | symbol. Common modifiers include preventDefault, stopPropagation, once, capture. Example: <form on:submit|preventDefault={handleSubmit}>.
Custom events are created using createEventDispatcher. Import from svelte, initialize in component, then dispatch events. Example: const dispatch = createEventDispatcher(); dispatch('custom', data);
Component events are listened to using on:eventName. Parent components can listen to dispatched events. Example: <Child on:custom={handleCustom}>. Events bubble by default.
Event forwarding passes events up through components using on:eventName. No handler needed for forwarding. Example: <button on:click>. Useful for bubbling events through component hierarchy.
Inline handlers can be defined directly in the on: directive. Example: <button on:click={() => count += 1}>. Good for simple operations but avoid complex logic.
Event delegation handles events at a higher level using bubbling. Attach single handler to parent for multiple children. Use event.target to identify source. Improves performance for many elements.
Data is passed as second argument to dispatch. Example: dispatch('custom', { detail: value }). Accessed in handler through event.detail. Supports any serializable data.
Event object contains event details passed to handlers. Includes properties like target, currentTarget, preventDefault(). Available as first parameter in event handlers.
Multiple events use multiple on: directives. Example: <div on:click={handleClick} on:mouseover={handleHover}>. Each event can have its own modifiers and handlers.
Stores in Svelte are reactive data containers that can be shared across components. They provide a way to manage global state and notify subscribers when data changes. Created using writable(), readable(), or derived().
Writable stores are created using writable() from svelte/store. Example: const count = writable(0). They provide set() and update() methods to modify values, and subscribe() to react to changes.
The store contract requires an object with subscribe method that takes a callback and returns unsubscribe function. Any object meeting this contract can be used as a store with $ prefix.
Store changes can be subscribed to using subscribe method or $ prefix in components. Example: count.subscribe(value => console.log(value)) or use $count directly in template.
Readable stores are created using readable() and are read-only. They can only be updated through their start function. Useful for external data sources that components shouldn't modify.
Derived stores are created using derived() and compute values based on other stores. Example: const doubled = derived(count, $count => $count * 2). Update automatically when source stores change.
Auto-subscription happens when using $ prefix with stores in components. Svelte automatically handles subscribe and unsubscribe. No manual cleanup needed. Works in template and script.
Store values can be updated using set() or update() methods. Example: count.set(10) or count.update(n => n + 1). Updates notify all subscribers automatically.
Stores are initialized with initial value in creation. Example: writable(initialValue). Can be undefined. Support synchronous and asynchronous initialization.
Stores integrate with Svelte's reactivity system. Changes trigger reactive updates. Work with reactive declarations ($:). Support reactive dependencies tracking.
Transitions in Svelte are built-in animations that play when elements are added to or removed from the DOM. They are added using the transition: directive, with built-in functions like fade, fly, slide, etc.
Fade transition is used with transition:fade directive. Example: <div transition:fade>. Can accept parameters like duration and delay. Animates opacity from 0 to 1 or vice versa.
in: and out: directives specify different transitions for entering and leaving. Example: <div in:fade out:fly>. Allows different animations for element addition and removal.
Transition parameters customize animation behavior. Example: transition:fade={{duration: 300, delay: 100}}. Include properties like duration, delay, easing function.
Fly transition animates position and opacity. Example: <div transition:fly={{y: 200}}>. Parameters include x, y coordinates, duration, opacity settings.
Slide transition animates element height. Example: <div transition:slide>. Useful for collapsible content. Can customize duration and easing.
Easing functions define animation progression. Import from svelte/easing. Example: transition:fade={{easing: quintOut}}. Affects animation timing and feel.
transition:local restricts transitions to when parent component is added/removed. Prevents transitions during internal state changes. Example: <div transition:fade|local>.
Scale transition animates size and opacity. Example: <div transition:scale>. Parameters include start, opacity, duration. Useful for pop-in effects.
Draw transition animates SVG paths. Example: <path transition:draw>. Parameters include duration, delay, easing. Useful for path animations.
Slots are placeholders in components that allow parent components to pass content. Defined using <slot> element. Enable component composition and content projection. Basic slots receive any content passed between component tags.
Default slots provide fallback content. Example: <slot>Default content</slot>. Content appears when parent doesn't provide slot content. Useful for optional content.
Named slots target specific slot locations using name attribute. Example: <slot name='header'>. Content provided using slot='header' attribute. Allows multiple distinct content areas.
Content is passed to named slots using slot attribute. Example: <div slot='header'>Header content</div>. Must match slot name in component. Can pass any valid HTML or components.
Slot props pass data from child to parent through slots. Use let:propertyName directive. Example: <slot name='item' let:item>. Enables parent to access child component data.
Use $$slots object to check slot content. Example: {#if $$slots.header}. Available in component script and template. Useful for conditional rendering.
Fallback content appears when slot is empty. Defined between slot tags. Example: <slot>Fallback</slot>. Provides default UI when parent doesn't provide content.
Slots enable flexible component composition. Support content injection at multiple points. Allow component reuse with different content. Enable layout component patterns.
Slot content maintains parent component scope. Can access parent variables and functions. Cannot directly access child component state. Uses parent component context.
Slot content can be styled in both parent and child. Child styles using :slotted() selector. Parent styles apply normally. Support style encapsulation.
Slots are placeholders in components that allow parent components to pass content. Defined using <slot> element. Enable component composition and content projection. Basic slots receive any content passed between component tags.
Default slots provide fallback content. Example: <slot>Default content</slot>. Content appears when parent doesn't provide slot content. Useful for optional content.
Content is passed to named slots using slot attribute. Example: <div slot='header'>Header content</div>. Must match slot name in component. Can pass any valid HTML or components.
Slot props pass data from child to parent through slots. Use let:propertyName directive. Example: <slot name='item' let:item>. Enables parent to access child component data.
Use $$slots object to check slot content. Example: {#if $$slots.header}. Available in component script and template. Useful for conditional rendering.
Fallback content appears when slot is empty. Defined between slot tags. Example: <slot>Fallback</slot>. Provides default UI when parent doesn't provide content.
Slots enable flexible component composition. Support content injection at multiple points. Allow component reuse with different content. Enable layout component patterns.
Slot content maintains parent component scope. Can access parent variables and functions. Cannot directly access child component state. Uses parent component context.
Slot content can be styled in both parent and child. Child styles using :slotted() selector. Parent styles apply normally. Support style encapsulation.
SvelteKit provides file-based routing where files in the routes directory automatically become pages. URLs correspond to file paths. Supports dynamic routes, nested layouts, and route parameters.
Create a route by adding a +page.svelte file in the routes directory. Example: src/routes/about/+page.svelte becomes '/about'. File structure mirrors URL structure.
Dynamic routes use square brackets in file names. Example: [slug]/+page.svelte creates dynamic segment. Parameters available through page store. Support multiple dynamic segments.
Route parameters accessed through page.params. Example: export let data; const { slug } = data. Available in +page.svelte and +page.server.js files.
Layout files (+layout.svelte) provide shared UI for multiple routes. Define common elements like navigation, footer. Support nested layouts. Content injected via <slot>.
Navigation uses <a> tags or programmatic goto function. SvelteKit handles client-side navigation. Supports prefetching with data attribute. Maintains scroll position.
Route groups organize routes using (group) syntax. Don't affect URL structure. Share layouts within groups. Support multiple groups. Help organize large applications.
Data loading uses +page.js or +page.server.js files. Export load function for data fetching. Returns props for page component. Supports server-side loading.
Error page (+error.svelte) handles route errors. Displays when errors occur. Access error details through error prop. Support custom error handling.
Redirects use redirect function from @sveltejs/kit. Can redirect in load functions or actions. Support temporary/permanent redirects. Handle authentication redirects.
The Context API allows passing data through the component tree without prop drilling. Uses setContext and getContext functions. Context is available to component and its descendants. Useful for sharing data/functionality.
Context is set using setContext function from svelte. Example: setContext('key', value). Must be called during component initialization. Value can be any type including functions.
Context is retrieved using getContext function. Example: const value = getContext('key'). Must use same key as setContext. Available in component and child components.
Context keys must be unique within component tree. Often use symbols for guaranteed uniqueness. Example: const key = Symbol(). Prevents key collisions between different contexts.
Context exists throughout component lifecycle. Created during initialization. Available until component destruction. Cannot be changed after initialization. New values require component reinitialization.
Common uses include theme data, localization, authentication state, shared functionality. Useful for cross-cutting concerns. Avoids prop drilling. Supports component composition.
Functions can be shared through context. Example: setContext('api', { method: () => {} }). Allows child components to access shared methods. Supports dependency injection pattern.
Context is scoped to component and descendants. Not available to parent or sibling components. Multiple instances create separate contexts. Follows component hierarchy.
getContext returns undefined if context not found. Should handle undefined case. Can provide default values. Consider error handling for required context.
Context is static, set during initialization. Stores are reactive, can change over time. Context good for static values/dependencies. Stores better for changing state.
Bindings create two-way data flow between DOM elements and variables using bind: directive. Example: <input bind:value={text}>. Updates flow both ways, DOM to variable and variable to DOM.
Basic form bindings include value for text inputs, checked for checkboxes, group for radio/checkbox groups. Example: <input bind:value>, <input type='checkbox' bind:checked>.
use: directive attaches actions (reusable DOM node functionality) to elements. Example: <div use:action>. Actions can have parameters. Support cleanup through returned function.
class: directive conditionally applies CSS classes. Example: <div class:active={isActive}>. Shorthand available when variable name matches class name.
Custom component binding uses bind: on exported props. Component must export the variable. Example: <CustomInput bind:value>. Supports two-way binding.
style: directive sets inline styles conditionally. Example: <div style:color={textColor}>. Can use shorthand when variable name matches style property.
Select elements bind using value or selectedIndex. Example: <select bind:value={selected}>. Supports multiple selection with array binding.
this binding references DOM element or component instance. Example: <div bind:this={element}>. Useful for direct DOM manipulation or component method access.
bind:group groups radio/checkbox inputs. Binds multiple inputs to single value/array. Example: <input type='radio' bind:group={selected} value='option'>.
Contenteditable elements bind using textContent or innerHTML. Example: <div contenteditable bind:textContent={text}>. Supports rich text editing.
Server-Side Rendering (SSR) generates HTML on the server instead of client. Provides better initial page load, SEO benefits. SvelteKit handles SSR automatically with hydration on client-side.
Hydration is the process where client-side JavaScript takes over server-rendered HTML. Makes static content interactive. Preserves server-rendered state. Happens automatically in SvelteKit.
Server-side data loading uses load functions in +page.server.js. Returns data for page rendering. Supports async operations. Data available during SSR and hydration.
Client-Side Rendering (CSR) fallback handles cases where SSR fails or is disabled. Uses +page.js instead of +page.server.js. Provides graceful degradation.
Disable SSR using export const ssr = false in +page.js. Page renders only on client. Useful for browser-specific functionality. Impacts initial page load.
Server-only modules run exclusively on server. Use .server.js extension. Cannot be imported by client code. Useful for sensitive operations like database access.
SSR errors handled by error.svelte pages. Support error boundaries. Can provide fallback content. Error details available through error prop.
Streaming SSR sends HTML in chunks as it's generated. Improves Time To First Byte (TTFB). Supports progressive rendering. Available through Response.body.
Environment variables accessed through $env/static/private or $env/dynamic/private. Only available server-side. Must prefix with VITE_ for client access.
Prerendering generates static HTML at build time. Uses export const prerender = true. Improves performance. Suitable for static content.
Vitest is the recommended testing framework for Svelte applications. It's fast, provides good integration with SvelteKit, and supports component testing. Jest can also be used but requires additional configuration.
Component tests use @testing-library/svelte. Mount components using render method. Test component behavior and DOM updates. Example: import { render } from '@testing-library/svelte'; const { getByText } = render(Component);
Svelte Inspector is a development tool enabled with 'ctrl + shift + i'. Shows component hierarchy, props, state. Helps debug component structure and data flow. Available in development mode.
Async tests use async/await syntax. Test async operations using act function. Handle promises and timeouts. Example: await fireEvent.click(button); await findByText('result');
Testing matchers verify component state/behavior. Include toBeInTheDocument, toHaveTextContent, toBeVisible. Provided by @testing-library/jest-dom. Support custom matchers.
Store state can be debugged using $store syntax. Subscribe to store changes. Log state updates. Use Svelte devtools. Monitor store mutations.
Testing hierarchy includes unit tests, integration tests, end-to-end tests. Focus on component isolation. Test component interaction. Verify application flow.
Event handlers tested using fireEvent. Simulate user interactions. Verify event outcomes. Example: fireEvent.click(button); expect(result).toBe(expected);
Snapshot testing captures component output. Compares against stored snapshots. Detects UI changes. Example: expect(container).toMatchSnapshot();
Props testing verifies component behavior with different props. Test prop types and values. Handle prop updates. Verify component rendering.
Svelte achieves performance through compile-time optimization. Generates vanilla JavaScript with minimal runtime overhead. Uses surgical DOM updates. Eliminates virtual DOM overhead.
Code splitting automatically breaks application into smaller chunks. Routes loaded on demand. Reduces initial bundle size. Uses dynamic imports. Improves load time.
Svelte compiles reactive statements into efficient JavaScript. Updates only affected DOM elements. No diffing required. Uses fine-grained reactivity system. Minimizes overhead.
Asset optimization includes minification, bundling, compression. Uses Vite for build process. Optimizes images and styles. Supports cache headers. Improves load performance.
Component optimization includes proper key usage, avoiding unnecessary updates, using tick() function. Implement efficient loops. Minimize state changes. Use proper event handling.
Lazy loading defers loading of components until needed. Uses dynamic imports. Supports route-level code splitting. Improves initial load time. Reduces bundle size.
Memory leak prevention includes proper cleanup in onDestroy, unsubscribing from stores, removing event listeners. Clear intervals/timeouts. Handle component disposal.
Prefetching loads route data before navigation. Uses sveltekit:prefetch directive. Improves perceived performance. Supports hover-based prefetching. Reduces loading time.
Store optimization includes batching updates, using derived stores efficiently, implementing selective updates. Minimize store subscribers. Handle update frequency.
Tree-shaking removes unused code during build. Reduces bundle size. Supported by default. Works with ES modules. Eliminates dead code.
Understand concepts like reactivity, components, stores, and lifecycle methods.
Work on creating components and implementing state management solutions.
Dive into animations, transitions, and advanced compiler features.
Expect hands-on challenges to build, optimize, and debug Svelte applications.
Join thousands of successful candidates preparing with Stark.ai. Start practicing Svelte questions, mock interviews, and more to secure your dream role.
Start Preparing now