ReactSvelte
Rosetta Stone.

Know some React or Svelte and curious about the other side? Translate everyday patterns between modern React and Svelte, one side-by-side example at a time. Read on for how the two frameworks differ at a high level, or dive right in with Component Basics.

React vs Svelte Conceptual Overview

Two answers to one question

Every UI framework answers the same question: when state changes, how do we ensure that the view catches up promptly and consistently? React re-runs your component in the browser to build a virtual DOM, a lightweight description of the view held in memory, and compares it with the previous one to find what changed in the real DOM. In contrast, Svelte does its work before your app ships. It compiles each component at build time into JavaScript that updates the DOM directly. Each piece of state already knows which parts of the view read it, so a change goes straight to those parts, with no virtual DOM to build or compare.

The two also differ in their scope and ambition. React’s core is more limited and leaves routing, styling, and most shared state to libraries you choose. Svelte – together with the SvelteKit web framework – builds much more in by default. The same abstraction for state updates in one component also works for sharing state across components without the need for an external library.

The lessons that follow come back to these two differences: React’s re-render and compare versus Svelte’s compile and notify; React plus assembling your own stack versus Svelte & SvelteKit with batteries included.

React: re-render, then compare

At build time, JSX becomes ordinary function calls. React Compiler, if enabled, adds memoization.

  1. setCount(count + 1) schedules a render.
  2. React calls Counter() again, and by default every child it renders.
  3. React compares the new virtual DOM with the previous one.
  4. React commits only the DOM nodes that differ.

State is a snapshot: until that render, count keeps its old value, and objects and arrays are replaced rather than changed in place.

The work happens in the browser, and React’s scheduler can pause it. That is how React keeps typing responsive during a slow render, and how Suspense waits for data before showing a part of the tree.

Svelte: compile, then notify

At build time, the compiler turns each .svelte file into code that creates the DOM and subscribes each reactive read to its state.

  1. count was declared with $state, so count = count + 1 writes to a signal, a value that tracks which code reads it.
  2. The signal notifies only the code that read count.
  3. Svelte updates that one text node or attribute.

State is live: count holds the new value as soon as you assign it, and objects and arrays can be changed in place.

The component’s <script> runs once per instance. Nothing re-runs the component, and there is no virtual DOM to compare.

React’s docs call the two phases render and commit. What Runs on Each Render lets you click a button and count which code runs again in each framework.

Where they agree

The two frameworks share more ideas than they differ on. Most skills carry over, and most lessons translate a pattern rather than replace it.

  • Components in a tree

    A UI is a tree of components. Props flow down, and children report back through callbacks. React spells out a form field as a value plus onChange, and Svelte also offers two-way binding with bind:value when you ask for it.

  • Declarative markup

    You describe the UI for the current state and the framework updates the DOM. Both use keys to track list items, and both need you to touch the DOM directly only for focus, measurement, and third-party widgets.

  • Effects as an escape hatch

    useEffect and $effect both exist to synchronize with systems outside the framework, and both sets of docs warn against using them to compute values.

  • Composition and context

    Children and snippets pass markup into a component. Context gives distant descendants a value without passing props through every layer.

  • The same toolchain

    TypeScript, Vite, npm packages, and plain browser APIs work the same way in both. A library that doesn’t touch the UI works in either.

  • Full-stack frameworks

    Next.js and React Router correspond to SvelteKit. Each has nested routes and layouts, server rendering, streaming, and forms that submit without JavaScript.

Performance Comparison

Svelte’s compiler-based approach can be much faster: over 10× faster than React’s streaming renderer at rendering HTML on the server, and nearly 7× faster at reordering rows in a list. Svelte’s biggest gains over React come in the work React adds on top of the DOM: rendering HTML on the server, comparing output after a change, and loading its runtime.

  • 4.8–10.4×faster server rendering of the same HTML
  • 6.8×faster at swapping two rows in a list
  • 5.3×smaller JavaScript download
  • 3.7×faster first paint
Measurement React SvelteReact ÷ Svelte
On the server Measured for this guide · React 19.3.1, Svelte 5.59.2
Render 1,000 rows to HTMLReact renderToString(), Svelte render()0.466 ms0.097 ms4.8×
The same, with React’s streaming rendererReact renderToReadableStream(), Svelte render()1.012 ms0.097 ms10.4×
In the browser js-framework-benchmark, Chrome 158 · React 19.2, Svelte 5.42
Create 1,000 rows24.6 ms21.7 ms1.1×
Update every 10th row14.1 ms10.6 ms1.3×
Select a row5.5 ms4.8 ms1.1×
Swap two rows87.4 ms12.8 ms6.8×
Clear 1,000 rows16.4 ms10.3 ms1.6×
Create 10,000 rows341.6 ms223.3 ms1.5×
Overall slowdown1.00 is the fastest entry1.55×1.18×1.3×
Memory after page load1.18 MB0.67 MB1.8×
Memory after adding 1,000 rows4.39 MB2.86 MB1.5×
Compressed JavaScript51.4 kB9.7 kB5.3×
First paint228.9 ms61.8 ms3.7×

Reading the results

  • On the server, Svelte compiles a separate version of each component that joins strings together, while React builds an element tree and walks it on every request. React’s streaming renderer, which frameworks such as Next.js use so that Suspense can send HTML in pieces, takes 2.2× as long as renderToString(). These times cover the renderer alone, not routing or data loading.
  • Creating rows is close, because building DOM nodes costs the same in any framework. The gap widens on updates, where React re-runs components and compares their output.
  • Swapping two rows is nearly 7× slower in React. When an item moves, React’s list comparison moves the DOM nodes of every row between the two swapped rows, not just the two that changed.
  • React uses almost double the memory before the page does anything, and its page takes 3.7× as long to paint, mostly because it loads and runs 5.3× as much JavaScript.

Why Svelte

Less code for the same result

State declared with $state reads and writes like a plain variable, so count = count + 1 and todos.push(item) update the view. A $derived value reads its inputs rather than listing them in a dependency array. Across the 29 lessons in this guide, the Svelte examples have 517 non-blank lines and the React examples have 693. That is 25% fewer lines and 13% fewer tokens, and Svelte is shorter in 27 of the 29 lessons. Most of the savings come from boilerplate such as setter calls, imports, closing JSX, and separate CSS files.

Batteries included, with fewer abstractions

Scoped styles, transitions, and two-way bindings are part of the language, and svelte/reactivity adds reactive versions of Map, Set, Date, and URL. State also works the same way at every scale. Where React shares state by lifting it into a parent, providing it through Context, or adding a store library like MobX or Jotai, the $state that drives one component can move into a .svelte.ts module that any component imports, as Shared State & Reuse shows. For whole apps, React’s docs recommend frameworks from other companies, such as Next.js from Vercel or React Router from Shopify. Svelte’s docs recommend SvelteKit, built by the Svelte team, which adds routing, data loading, form actions, server rendering, and adapters for deploying to different hosts. That leaves fewer libraries to choose between and fewer abstractions to learn, and the pieces are designed to work together.

The compiler keeps track of updates

The compiler sees which values the markup reads, so there is nothing to memoize, no stale closure to debug, and no rule about the order of Hook calls. React Compiler removes most hand-written useMemo, useCallback, and memo, but it does this by skipping parts of a re-render. Svelte has no re-render to skip. Compiler & Memoization compares the two compilers on the same component.

Smaller, faster output

Because the compiler moves work from the browser into the build, Svelte ships less JavaScript and does less of it on each update. In the measurements above, React ships 5.3× as much JavaScript, takes 3.7× as long to paint, and takes 4.8–10.4× as long to render the same HTML on the server.

Markup that reads like HTML

Attributes keep their HTML names, such as class and for. Events are plain onclick attributes, and logic lives in blocks such as {#if} and {#each}. You can usually paste HTML into a component unchanged.

Why React

A much larger ecosystem

In the week of November 22 to 28, 2026, npm served react about 253 million times and svelte about 9.8 million times, a 26× difference. Those counts include automated installs, but the gap shows up everywhere else too. React has more component libraries, design systems, SDKs that ship React components first, answers to search for, and developers to hire.

Mature async and server features

React can pause a slow render to keep typing responsive with transitions and useDeferredValue, wait for data with Suspense, and split one component tree between server and client with Server Components. Svelte 5 can’t pause a render, so the Svelte example in Responsive Input & Deferred Updates debounces instead, and Svelte has no component-level split between server and client. Its newer async features are still experimental as of Svelte 5.59 and SvelteKit 3.4: using await inside a component needs Svelte’s experimental.async flag, and SvelteKit’s remote functions need experimental.remoteFunctions as well. Without those flags, SvelteKit load functions fetch the data and {#await} blocks show pending promises.

Backing

Since February 2026, React and React Native have belonged to the React Foundation, hosted by the Linux Foundation, whose founding members include Meta, Microsoft, Amazon, and Vercel. Svelte is an independent open-source project with a smaller core team. Its creator, Rich Harris, has worked on it full-time at Vercel since late 2021.

Start with Component Basics if either framework is new to you, or use search to jump to a pattern you need.

Foundations

Component Basics

Read one small component in each framework: props coming in, local state, a click handler, a condition, and styles. Read this first if either framework is new to you.

Two ways to write a component

A React component lives in a .jsx or .tsx file, whose HTML-like JSX syntax mixes code and markup, and the file usually imports its styles from a stylesheet. Each component is a plain JavaScript function with a capitalized name that receives its props as one object and returns JSX, which compiles to ordinary function calls. One file can hold as many components as you need. Functions whose names start with use, such as useState, are Hooks. They give a component state and other features, and they must be called at the top level of the component. React is a library, so a framework such as Next.js or React Router supplies routing, builds, and server rendering, while a client-only app can use a bundler such as Vite.

A Svelte component can be more self-contained. It’s a .svelte file with up to three distinct parts: a <script> block, markup, and a <style> block. Each .svelte file holds exactly one component, so every new component gets its own file. Markup that repeats within one component can go in a {#snippet} declared in the same file, which works like a small local component. The Svelte compiler turns the file into JavaScript. Keywords that start with $, called runes, mark reactive code: $props() reads props, $state creates state, and $derived computes a value from other state. Markup uses braces for expressions and blocks such as {#if} for logic. SvelteKit is the official framework for routing, builds, and server rendering.

React

Greeting.tsx
import { useState } from 'react';
import './greeting.css';

type Props = { name: string; excited?: boolean };

export default function Greeting(
  { name, excited = false }: Props
) {
  const [waves, setWaves] = useState(0);
  const punctuation = excited ? '!' : '.';

  return (
    <section className="greeting">
      <h2>Hello, {name}{punctuation}</h2>
      <button onClick={() => setWaves(n => n + 1)}>
        Wave
      </button>{' '}
      {waves > 0 && <span>{'👋'.repeat(waves)}</span>}
    </section>
  );
}
greeting.css
.greeting h2 { color: rebeccapurple; }
App.tsx
import Greeting from './Greeting';

export default function App() {
  return <Greeting name="Ada" excited />;
}

Svelte

Greeting.svelte
<script lang="ts">
  let { name, excited = false }: {
    name: string;
    excited?: boolean;
  } = $props();
  let waves = $state(0);
  let punctuation = $derived(excited ? '!' : '.');
</script>

<section>
  <h2>Hello, {name}{punctuation}</h2>
  <button onclick={() => waves++}>Wave</button>
  {#if waves > 0}<span>{'👋'.repeat(waves)}</span>{/if}
</section>

<style>
  h2 { color: rebeccapurple; }
</style>
App.svelte
<script lang="ts">
  import Greeting from './Greeting.svelte';
</script>

<Greeting name="Ada" excited />

Worth knowing

Different rules to learn

React’s rules are about calling. A component must be pure while it renders, and Hooks must run in the same order every time. Svelte’s rules are about reading. Updates follow the values that markup, $derived, or $effect read, so a value copied into a plain variable stops updating. What Runs on Each Render shows how that difference plays out.

Foundations

State & Reactivity

See how React’s state snapshots and Svelte’s subscriptions handle a counter and a todo list.

Snapshots and subscriptions

React state lives in useState, which returns the current value and a setter. Each render works from a snapshot: the state as it was when React called the component. React can’t observe a write to a plain JavaScript value, so calling the setter is how it learns about a change. It compares the new value with the old one using Object.is and, if they differ, calls the component again to produce the next snapshot.

Svelte state is a variable declared with $state, and you change it by simply assigning to it. Reading it in markup, $derived, or $effect subscribes to it. The compiler turns count++ into a write that automatically notifies every subscriber, and Svelte updates only the parts of the page that read count. There’s no need for each render to take a snapshot, so every read sees the current value.

What Runs on Each Render follows both models in more detail.

React

Counter.tsx
import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(n => n + 1)}>
      Count: {count}
    </button>
  );
}

Svelte

Counter.svelte
<script lang="ts">
  let count = $state(0);
</script>

<button onclick={() => count++}>
  Count: {count}
</button>

React gotcha

Calling setCount(count + 1) three times adds 1, not 3

Because count keeps its old value until the next render, if the count is 0, every call below computes 0 + 1 and asks React for 1.

Adds 1Passing the next value
Counter.tsx
function handleClick() {
  setCount(count + 1); // 0 → 1
  setCount(count + 1); // 0 → 1
  setCount(count + 1); // 0 → 1
}
Adds 3Passing an updater function
Counter.tsx
function handleClick() {
  setCount(n => n + 1); // 0 → 1
  setCount(n => n + 1); // 1 → 2
  setCount(n => n + 1); // 2 → 3
}

React runs queued updater functions in order and passes each one the result of the one before, so the updates build on each other.

Is passing a value always wrong?

No. It’s fine and clearer if the new state doesn’t depend on the old one, as in setName(event.target.value) or setOpen(false). But use an updater when the next value is calculated from the previous one. This matters most in code that runs after an await or in a timer, where count can be several renders old.

Worth knowing

Why React replaces state and uses updater functions

TodoList.tsx
// Inside the TodoList component
const [todos, setTodos] =
  useState<Todo[]>([]);

function add(todo: Todo) {
  setTodos(todos => [...todos, todo]);
}

function toggle(id: number) {
  setTodos(todos => todos.map(t => (
    t.id === id
      ? { ...t, done: !t.done }
      : t
  )));
}

function remove(id: number) {
  setTodos(todos =>
    todos.filter(t => t.id !== id)
  );
}

React data flows one-way. A component owns its state, passes it down as props, and changes it only through its setter. Because only the owner’s setter starts a render, a child that mutates data it was handed changes it without the owner knowing. todos.push(todo) changes the array in place: the same array the current render and every child already hold. React never hears about it, and setTodos(todos) passes the same array, so Object.is sees no change and the update is skipped.

Write setTodos(todos => [...todos, todo]) instead. The spread builds a new array, and the arrow form is an updater function, so several updates in one event build on each other, as the React gotcha above shows. To change one entry, use map. To remove one, use filter.

Why Svelte can safely mutate state

TodoList.svelte
<script lang="ts">
  let todos = $state<Todo[]>([]);

  function add(todo: Todo) {
    todos.push(todo);
  }

  function toggle(todo: Todo) {
    // A todo from {#each todos as todo}
    todo.done = !todo.done;
  }

  function remove(id: number) {
    // Replacing the array works too.
    todos = todos.filter(t => t.id !== id);
  }
</script>

In Svelte, todos.push(todo) is a real mutation that also notifies every reader. A $state array or object is a proxy that does for each property what count++ does for a variable, so todo.done = !todo.done updates whatever reads done. You get an old value only by copying it out: let { done } = todo reads done once, as it would in plain JavaScript.

Notifications keep every reader current, but they don’t say who may write. For props, Svelte follows the same rule as React: the owner changes the state. A child may reassign a prop as a temporary local override, which lasts until the parent sends a new value. Mutating a $state proxy received as a prop still updates the page, but it triggers an ownership_invalid_mutation warning in development. Mutating a plain object prop changes the object but updates nothing on the page. Send changes up with a callback, as in React, or opt both sides into sharing with $bindable and bind:, as in Bindable & Controlled Inputs.

State you share on purpose, by importing it from a module or reading it from context, is different: any component that has it may write to it, as Shared State & Reuse and Context & Prop Drilling show. Together these make mutation safe: notifications rule out stale reads, and the ownership rule for props, backed by the development warning, keeps those writes with the owner.

What Svelte’s $state proxy can’t see

Svelte’s $state proxies only arrays and plain objects. Class instances, Map, Set, Date, and URL stay as they are, so map.set(key, value) on a Map held in $state tells no one. Proxying also stops at the first value that isn’t an array or plain object, so a class instance nested inside a $state object isn’t proxied either. Reassigning a let variable still notifies, as in plain = new Map(plain) in the example, because the $state variable is reactive even when its contents aren’t. $state.raw skips the proxy on purpose, even for arrays and plain objects: only reassigning it updates the page, as with React state.

For the built-ins, import SvelteMap, SvelteSet, SvelteDate, or SvelteURL from svelte/reactivity. They’re drop-in versions with the same methods: write new SvelteMap() instead of new Map(). Reading get(key) or size subscribes, and set or delete notifies readers, the way a proxy does for an array. You don’t need $state around them unless you plan to reassign the variable. The values stored in a SvelteMap or SvelteSet aren’t made deeply reactive, so if a SvelteMap holds plain objects, setting a property on one, such as .done = true, notifies no one. Store objects that are reactive themselves if you need that.

To make your own reactive type, give a class $state fields, which the compiler turns into getters and setters that subscribe and notify. To wrap a source that lives outside Svelte, such as a browser event, use createSubscriber, as in External Stores & Browser APIs.

Code outside Svelte may not expect a proxy either. structuredClone throws on one, and console.log prints it as a Proxy, which Svelte warns about in development. Pass $state.snapshot(todos) to hand over a plain copy, or log with $inspect(todos), which in development logs again whenever todos changes.

votes.svelte.ts
import { SvelteMap } from 'svelte/reactivity';

// Don’t do this. Map isn’t proxied,
// so set() notifies no one.
let plain = $state(new Map<string, number>());
plain.set('svelte', 1);

// Reassigning does notify: the variable is
// reactive even though its contents aren’t.
plain = new Map(plain);

// Same methods as Map. get() and size subscribe,
// set() and delete() notify.
const votes = new SvelteMap<string, number>();
votes.set('svelte', 1);

// Your own type: each $state field becomes a
// getter and setter that subscribe and notify.
class Tally {
  count = $state(0);
  add() {
    this.count++;
  }
}

const tally = new Tally();
tally.add(); // Notifies readers of tally.count

Foundations

What Runs on Each Render

Click a toolbar button and follow which code runs again. React calls the component function again, along with its children. Svelte updates only the text that reads the state.

Re-running a function vs running a script once

A React component is a function that React calls to describe the UI. Each state change calls Toolbar again from the top. It logs, creates a fresh options object, and returns new JSX. React renders Status as well, because by default a parent’s render includes its children even when their props look the same. React then compares the result with the previous one and updates only the DOM that changed: the button text.

A Svelte component’s <script> runs once, when the instance is created. The compiler connects each reactive read in the markup to the DOM it controls. Clicking the button changes clicks and Svelte updates one text node. Status’s script doesn’t run again either, and it wouldn’t even if options changed: Svelte would update only the text that reads options.tone.

Because the body runs on every render, React matches each Hook to its stored state by call order. On later renders, useState(0) returns the current count and ignores its argument. Call Hooks at the top level of the component, never inside a condition, a loop, or after an early return, so the order stays the same.

Every object, array, and function created in the body is new on each render. React compares Effect dependencies and context values with Object.is, and a component wrapped in memo compares each prop the same way, so this render’s options never equals the last one. Strings and numbers such as 'calm' compare equal. Identity matters once a value reaches a memoized calculation, an Effect’s dependency list, a context provider, or a child wrapped in memo. Svelte has no equivalent concern for options, because the script that creates it runs only once.

React

Toolbar.tsx
import { useState } from 'react';

type Options = { tone: string };

function Status({ options }: { options: Options }) {
  console.log('Status render');  // Each time Toolbar renders
  return <p>Tone: {options.tone}</p>;
}

// Shown with React Compiler disabled.
export default function Toolbar() {
  const [clicks, setClicks] = useState(0);

  console.log('Toolbar render');  // Every render
  const options = { tone: 'calm' };  // A new object every render

  return (
    <>
      <button onClick={() => setClicks(n => n + 1)}>
        Clicked {clicks} times
      </button>
      <Status options={options} />
    </>
  );
}

Svelte

Toolbar.svelte
<script lang="ts">
  import Status from './Status.svelte';
  let clicks = $state(0);

  console.log('Toolbar script');  // Once per instance
  const options = { tone: 'calm' };  // Created once
</script>

<button onclick={() => clicks++}>Clicked {clicks} times</button>
<!-- {options} is short for options={options} -->
<Status {options} />
Status.svelte
<script lang="ts">
  let { options }: { options: { tone: string } } = $props();
  console.log('Status script');  // Once per instance
</script>

<p>Tone: {options.tone}</p>

Foundations

Derived Values

Filter a list from the current query without storing a second copy of the result.

React

Search.tsx
import { useState } from 'react';

export default function Search({ names }: { names: string[] }) {
  const [query, setQuery] = useState('');
  const matches = names.filter(name => name.includes(query));

  return (
    <>
      <input aria-label="Filter names" value={query}
        onChange={event => setQuery(event.target.value)} />
      <p>{matches.length} matches</p>
    </>
  );
}

Svelte

Search.svelte
<script lang="ts">
  let { names }: { names: string[] } = $props();
  let query = $state('');
  let matches = $derived(
    names.filter(name => name.includes(query))
  );
</script>

<input aria-label="Filter names" bind:value={query} />
<p>{matches.length} matches</p>

React with MobX

The directory owns both the names and the query. Its computed getter tracks the observable fields used by the filter and caches the result while a view observes it. A name count and a results list can share that work. If only one component filters a short array of ordinary React props, the inline React version has less setup. Create the model once per directory and use replaceNames when new data arrives. Compiler & Memoization explains the directive in the observer.

SearchModel.ts
import { makeAutoObservable } from 'mobx';

export class SearchModel {
  query = '';
  names: string[];

  constructor(names: string[]) {
    this.names = names;
    makeAutoObservable(this);
  }

  get matches() {
    return this.names.filter(name => name.includes(this.query));
  }

  setQuery(query: string) { this.query = query; }
  replaceNames(names: string[]) { this.names = names; }
}
Search.tsx
import { observer } from 'mobx-react-lite';
import type { SearchModel } from './SearchModel';

export default observer(function Search({ directory }: {
  directory: SearchModel;
}) {
  'use no memo';
  return (
    <>
      <input aria-label="Filter names" value={directory.query}
        onChange={event => directory.setQuery(event.target.value)} />
      <p>{directory.matches.length} matches</p>
    </>
  );
});

Worth knowing

Don’t copy a derived value into state

A common first attempt stores matches in useState and fills it from useEffect whenever names or query changes. The component first renders with the old matches, then renders again once the Effect sets the new ones. That second state can also drift from its inputs. Calculate the value during render instead. Svelte has the same trap: an $effect that copies a calculation into $state is a $derived in disguise.

Calculations that need statements

In React, a calculation that needs several statements simply goes in the component body. $derived takes a single expression, so for a loop or an early return, pass a function to $derived.by, as in $derived.by(() => { … }). It tracks whatever the function reads, as $derived does.

Foundations

Effects & Cleanup

Keep a status panel’s browser timer running while the panel is mounted. Each tick logs the current label at the chosen interval.

Why this timer needs an effect

Change the panel’s delay from 1,000 ms to 250 ms and the browser keeps firing the old interval every 1,000 ms until you clear it. The timer also needs to start when the panel mounts on page load, before anyone clicks a button.

In React, a setInterval call in the component body would start another interval each time the component renders. In Svelte, the same call at the top level of the script runs once per instance, but it only ever sees the initial delay. Both frameworks update the displayed label without any extra code.

React’s useEffect and Svelte’s $effect start the timer in the browser after the component mounts. When the delay changes, cleanup clears the old interval before setup starts a new one. On unmount, cleanup stops the timer. Neither runs during server rendering.

Use the same test elsewhere. Calculate display values, such as the delay in seconds, during render in React or with $derived in Svelte. Put a one-off action such as logging a button click in the event handler. Use an effect when a browser API, subscription, or connection needs to stay in sync with the component.

React

Timer.tsx
import { useEffect, useEffectEvent } from 'react';

type Props = { delay: number; label: string };

export default function Timer({ delay, label }: Props) {
  const onTick = useEffectEvent(() => console.log(label));

  useEffect(() => {
    const id = setInterval(() => onTick(), delay);
    return () => clearInterval(id);
  }, [delay]);

  return <p>{label}</p>;
}

Svelte

Timer.svelte
<script lang="ts">
  let { delay, label }: { delay: number; label: string } = $props();

  $effect(() => {
    const id = setInterval(() => console.log(label), delay);
    return () => clearInterval(id);
  });
</script>

<p>{label}</p>

Worth knowing

Svelte’s untrack and onMount

React’s useEffectEvent lets an Effect read the latest label without depending on it. In Svelte, wrap the read in untrack, as in untrack(() => label), and the effect won’t subscribe to it. The timer doesn’t need that, because its interval callback already runs outside the effect’s tracking. For setup that runs once after mount, React uses useEffect with an empty dependency list, and Svelte has onMount, which tracks nothing and calls the cleanup it returns on unmount.

Templates & Components

Markup: Templates & JSX

Render one task row with a class, an inline style, a labeled checkbox, a conditional badge, and trusted HTML notes. Most differences are spelling.

React

TaskRow.tsx
type Task = {
  id: string; title: string; notes: string;
  priority: number; done: boolean;
};

export default function TaskRow({ task, onToggle }: {
  task: Task;
  onToggle: (id: string) => void;
}) {
  return (
    <li className={task.done ? 'task done' : 'task'}
      style={{ opacity: task.done ? 0.6 : 1 }}>
      <input id={'task-' + task.id} type="checkbox"
        checked={task.done}
        onChange={() => onToggle(task.id)} />
      <label htmlFor={'task-' + task.id}>
        {task.title}
      </label>
      {task.priority > 0 && (
        <strong>Priority {task.priority}</strong>
      )}
      {/* notes is sanitized HTML from the server */}
      <div
        dangerouslySetInnerHTML={{ __html: task.notes }}
      />
    </li>
  );
}

Svelte

TaskRow.svelte
<script lang="ts">
  type Task = {
    id: string; title: string; notes: string;
    priority: number; done: boolean;
  };
  let { task, ontoggle }: {
    task: Task;
    ontoggle: (id: string) => void;
  } = $props();
</script>

<li class="task" class:done={task.done}
  style:opacity={task.done ? 0.6 : 1}>
  <input id={'task-' + task.id} type="checkbox"
    checked={task.done}
    onchange={() => ontoggle(task.id)} />
  <label for={'task-' + task.id}>{task.title}</label>
  {#if task.priority > 0}
    <strong>Priority {task.priority}</strong>
  {/if}
  <!-- notes is sanitized HTML from the server -->
  <div>{@html task.notes}</div>
</li>

Worth knowing

One expression per return

A component returns a single JSX expression, so sibling elements need a wrapper. A fragment, <>…</>, groups them without adding a DOM element. Inside a list, use <Fragment key={id}> so the group can take a key. A Svelte component can have any number of top-level elements.

Spelling, closing tags, and whitespace

aria-* and data-* attributes keep their hyphens in JSX, while others switch to the DOM name: tabIndex, readOnly, autoComplete. Every tag must close, as in <input />. Comments go in braces: {/* … */}. JSX also drops whitespace that contains a line break, so text on its own line after an element needs {' '} to keep a space before it.

Shorthand when the names match

JSX always spells out options={options}, and {options} on its own is a syntax error. Svelte lets you write the name once when an attribute’s value is a variable of the same name, so <Status {options} /> means <Status options={options} />. Directives and bindings shorten the same way: class:done means class:done={done}, and bind:value means bind:value={value}. Event handlers do too, as in <svelte:window {onkeydown} />.

Templates & Components

Conditionals & Lists

Render a keyed list with an empty state. Each row has a draft field that should stay with its task when the list is sorted.

React

Tasks.tsx
type Task = { id: string; title: string };

export default function Tasks({ tasks }: { tasks: Task[] }) {
  return (
    <ul>
      {tasks.length === 0 ? (
        <li>No tasks yet.</li>
      ) : (
        tasks.map(task => (
          <li key={task.id}>
            {task.title}
            <input aria-label={'Draft for ' + task.title} />
          </li>
        ))
      )}
    </ul>
  );
}

Svelte

Tasks.svelte
<script lang="ts">
  type Task = { id: string; title: string };
  let { tasks }: { tasks: Task[] } = $props();
</script>

<ul>
  {#each tasks as task (task.id)}
    <li>
      {task.title}
      <input aria-label={'Draft for ' + task.title} />
    </li>
  {:else}
    <li>No tasks yet.</li>
  {/each}
</ul>

React with MobX

Rename one task and follow the reads. The list reads membership and IDs. Each row reads its own title. A rename wakes the row that displays it, while reordering the array wakes the list. A stable React key still keeps a row’s local state with its task. The extra observer boundary pays off when individual items change frequently.

TaskList.ts
import { makeAutoObservable } from 'mobx';

export type Task = { id: string; title: string };

export class TaskList {
  tasks: Task[];

  constructor(tasks: Task[]) {
    this.tasks = tasks;
    makeAutoObservable(this);
  }

  rename(id: string, title: string) {
    const task = this.tasks.find(item => item.id === id);
    if (task) task.title = title;
  }
}
Tasks.tsx
import { observer } from 'mobx-react-lite';
import type { Task, TaskList } from './TaskList';

const TaskRow = observer(function TaskRow({ task }: { task: Task }) {
  'use no memo';
  return (
    <li>
      {task.title}
      <input aria-label={'Draft for ' + task.title} />
    </li>
  );
});

export default observer(function Tasks({ list }: { list: TaskList }) {
  'use no memo';
  return (
    <ul>
      {list.tasks.length === 0
        ? <li>No tasks yet.</li>
        : list.tasks.map(task => <TaskRow key={task.id} task={task} />)}
    </ul>
  );
});

Worth knowing

Change a key to start fresh

A key does more than match rows. Give any component a key and a new value replaces it with a fresh instance, discarding its state and re-running its setup. <Profile key={userId} /> clears a half-written draft when the user changes. Svelte does the same with {#key userId}<Profile />{/key}. Prefer this to an Effect that resets several pieces of state by hand.

Templates & Components

Props & Composition

Pass data down, send events up, and let a parent supply the card’s body.

How content passes between components

Both frameworks pass data down as props and send events up through callback props such as onClose. Neither has a separate event system for components: a callback is an ordinary function prop. Event handler props are spelled onClose in React and onclose in Svelte by convention, matching each framework’s DOM event names.

Markup between a component’s tags is passed differently. In React it arrives as the children prop, a JSX value that the component places wherever it likes. In Svelte it arrives as a children snippet, a reusable piece of markup that the component renders with {@render children()}. You can declare more snippets with {#snippet name(args)} and pass them as props, much like passing a render function in React.

React

Card.tsx
import type { ReactNode } from 'react';

type Props = {
  title: string;
  onClose: () => void;
  children: ReactNode;
};

export default function Card({ title, onClose, children }: Props) {
  return (
    <section>
      <h3>{title}</h3>
      {children}
      <button onClick={onClose}>Close</button>
    </section>
  );
}
Parent.tsx
import { useState } from 'react';
import Card from './Card';

export default function Parent() {
  const [open, setOpen] = useState(true);
  return open && (
    <Card title="Draft" onClose={() => setOpen(false)}>
      <p>Changes are saved locally.</p>
    </Card>
  );
}

Svelte

Card.svelte
<script lang="ts">
  import type { Snippet } from 'svelte';
  let { title, onclose, children }: {
    title: string;
    onclose: () => void;
    children: Snippet;
  } = $props();
</script>

<section>
  <h3>{title}</h3>
  {@render children()}
  <button onclick={onclose}>Close</button>
</section>
Parent.svelte
<script lang="ts">
  import Card from './Card.svelte';
  let open = $state(true);
</script>

{#if open}
  <Card title="Draft" onclose={() => open = false}>
    <p>Changes are saved locally.</p>
  </Card>
{/if}

Worth knowing

A render prop that receives the row

TaskList.tsx
import type { ReactNode } from 'react';

type Task = { id: string; title: string };

export default function TaskList({
  tasks, renderRow,
}: {
  tasks: Task[];
  renderRow: (task: Task) => ReactNode;
}) {
  return (
    <ul>
      {tasks.map(task => (
        <li key={task.id}>
          {renderRow(task)}
        </li>
      ))}
    </ul>
  );
}

TaskList owns the tasks and calls renderRow for each one, so the caller decides the markup without knowing how the list is built, as in renderRow={task => <b>{task.title}</b>}.

A snippet that receives the row

TaskList.svelte
<script lang="ts">
  import type { Snippet } from 'svelte';
  type Task = { id: string; title: string };
  let { tasks, row }: {
    tasks: Task[];
    row: Snippet<[Task]>;
  } = $props();
</script>

<ul>
  {#each tasks as task (task.id)}
    <li>{@render row(task)}</li>
  {/each}
</ul>

Snippet<[Task]> types the snippet’s argument, so the caller’s task is typed too. The caller declares the snippet between the component’s tags, as in {#snippet row(task)} inside <TaskList {tasks}>, and it arrives as the row prop.

Templates & Components

Bindable & Controlled Inputs

Edit a title in a child text field. The parent shows a live preview and can restore the original title.

One-way data with a callback, or a two-way binding

React data flows one-way. A controlled input receives its text as the value prop and reports each edit through onChange, and the owner of the state decides whether to store it. The same pattern extends to your own components: pass a value down and a callback to change it.

Svelte adds two-way bindings. bind:value keeps a variable and an input in sync in both directions. A component opts its own prop into the same treatment with $bindable, so a parent can write bind:value on it as well. Data still flows down by default; a binding is an explicit exception on both sides.

React

Editor.tsx
import { useState } from 'react';

function TitleField({ value, onValueChange }: {
  value: string;
  onValueChange: (value: string) => void;
}) {
  return (
    <label>Title <input value={value}
      onChange={event => onValueChange(event.target.value)} /></label>
  );
}

export default function Editor() {
  const [title, setTitle] = useState('Draft');
  return (
    <>
      <TitleField value={title} onValueChange={setTitle} />
      <p>Preview: {title}</p>
      <button onClick={() => setTitle('Draft')}>Reset</button>
    </>
  );
}

Svelte

TitleField.svelte
<script lang="ts">
  let { value = $bindable('') }: { value?: string } = $props();
</script>

<label>Title <input bind:value /></label>
Editor.svelte
<script lang="ts">
  import TitleField from './TitleField.svelte';
  let title = $state('Draft');
</script>

<TitleField bind:value={title} />
<p>Preview: {title}</p>
<button onclick={() => title = 'Draft'}>Reset</button>

Worth knowing

onChange fires on every keystroke

React’s onChange behaves like the DOM input event, not the DOM change event that waits for blur. Each edit calls the handler, which is what lets the preview stay live. For a checkbox, pair checked with onChange in React, or use bind:checked in Svelte.

A value without onChange is read-only

Passing value tells React to keep the field equal to that prop. With no onChange to update it, typing changes nothing and React warns in development. Add the handler, use defaultValue for a field you only read on submit, or add readOnly if that’s the intent.

Start a controlled field with a string

value={undefined} makes the input uncontrolled. If the value later becomes a string, React warns that the input switched from uncontrolled to controlled. Start with '', as the Svelte wrapper does with $bindable('').

Templates & Components

Styling Components

A status label and a task count reuse one badge. React applies classes from a plain stylesheet. Svelte keeps its CSS in the component’s style block.

React

Badge.tsx
import type { ReactNode } from 'react';
import './badge.css';

export default function Badge({ done = false, children }: {
  done?: boolean;
  children: ReactNode;
}) {
  const className = done ? 'task-badge task-badge--done' : 'task-badge';
  return <span className={className}>{children}</span>;
}
badge.css
.task-badge {
  border: 1px solid currentColor;
  border-radius: 1rem;
  padding: .25rem .75rem;
}

.task-badge--done {
  color: #19452a;
  background-color: #d8f3df;
}
Status.tsx
import Badge from './Badge';

export default function Status({ done }: { done: boolean }) {
  return <Badge done={done}>{done ? 'Done' : 'Pending'}</Badge>;
}
TaskCount.tsx
import Badge from './Badge';
import './task-count.css';

export default function TaskCount({ count }: { count: number }) {
  return (
    <output className="task-count">
      <Badge>{count} tasks</Badge>
    </output>
  );
}
task-count.css
.task-count { font-variant-numeric: tabular-nums; }

Svelte

Badge.svelte
<script lang="ts">
  import type { Snippet } from 'svelte';
  let { done = false, children }: {
    done?: boolean;
    children: Snippet;
  } = $props();
</script>

<span class:done>{@render children()}</span>

<style>
  span {
    border: 1px solid currentColor;
    border-radius: 1rem;
    padding: .25rem .75rem;
  }

  .done {
    color: #19452a;
    background-color: #d8f3df;
  }
</style>
Status.svelte
<script lang="ts">
  import Badge from './Badge.svelte';
  let { done }: { done: boolean } = $props();
</script>

<Badge {done}>{done ? 'Done' : 'Pending'}</Badge>
TaskCount.svelte
<script lang="ts">
  import Badge from './Badge.svelte';
  let { count }: { count: number } = $props();
</script>

<output style:font-variant-numeric="tabular-nums">
  <Badge>{count} tasks</Badge>
</output>

Worth knowing

Scoped styles stop at the child component

React’s plain CSS is global, so a parent can reach a child’s markup with any selector, and the usual pattern is a className prop that Badge merges with its own classes. Svelte’s scoping stops at the child: a rule in Status.svelte can’t style the span that Badge.svelte renders. Wrap the selector in :global(…) under a scoped parent, let Badge accept a class prop and apply it, or have Badge read a CSS custom property such as var(--badge-bg), which the parent sets with <Badge --badge-bg="…">.

CSS Modules give React file-level scoping

Many React projects use badge.module.css instead of a plain stylesheet. Importing it returns an object such as styles.done whose class names are made unique at build time. That gives a scoping guarantee close to Svelte’s without a naming convention. Vite and Next.js support it with no extra setup. Tailwind is the other common choice.

Conditional class lists

React’s className takes a string, and teams usually build it with the small clsx package. Since Svelte 5.16, class accepts objects and arrays directly, so class={['badge', { done }]} works without a helper. Svelte uses clsx internally for that feature.

Templates & Components

Generic Components

Build one picker that lists any kind of item. TypeScript infers the item type from the list, so the callback receives a typed user.

React

Picker.tsx
type Props<T> = {
  items: T[];
  label: (item: T) => string;
  onPick: (item: T) => void;
};

export default function Picker<T extends { id: string }>(
  { items, label, onPick }: Props<T>
) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          <button onClick={() => onPick(item)}>
            {label(item)}
          </button>
        </li>
      ))}
    </ul>
  );
}
UserPicker.tsx
import { useState } from 'react';
import Picker from './Picker';

type User = { id: string; name: string; email: string };

export default function UserPicker({ users }: {
  users: User[];
}) {
  const [chosen, setChosen] = useState<User | null>(null);
  return (
    <>
      <Picker items={users} label={user => user.name}
        onPick={setChosen} />
      <p>{chosen?.email ?? 'Nobody picked yet.'}</p>
    </>
  );
}

Svelte

Picker.svelte
<script lang="ts" generics="T extends { id: string }">
  let { items, label, onpick }: {
    items: T[];
    label: (item: T) => string;
    onpick: (item: T) => void;
  } = $props();
</script>

<ul>
  {#each items as item (item.id)}
    <li>
      <button onclick={() => onpick(item)}>
        {label(item)}
      </button>
    </li>
  {/each}
</ul>
UserPicker.svelte
<script lang="ts">
  import Picker from './Picker.svelte';
  type User = { id: string; name: string; email: string };
  let { users }: { users: User[] } = $props();
  let chosen = $state<User | null>(null);
</script>

<Picker items={users} label={user => user.name}
  onpick={user => chosen = user} />
<p>{chosen?.email ?? 'Nobody picked yet.'}</p>

Worth knowing

Reuse a component’s props type

Both frameworks export a ComponentProps helper. ComponentProps<typeof Card> from svelte or react gives the props a component accepts, which helps when a wrapper forwards most of them. For a native element in React, ComponentProps<'button'> lists every button attribute. Svelte’s equivalent is HTMLButtonAttributes from svelte/elements.

Application Patterns

Shared State & Reuse

Make two buttons show one count. A custom Hook shares logic, not state, so React lifts the count into a common parent or keeps it in a store such as MobX. In Svelte, both buttons import one $state object from a module.

React with a custom Hook

useCounter.ts
import { useState } from 'react';

// Shares the logic, not the state: each
// component that calls it gets its own count.
export function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(n => n + 1);
  return { count, increment };
}
Counters.tsx
import { useCounter } from './useCounter';

function Counter() {
  const { count, increment } = useCounter();
  return (
    <button onClick={increment}>{count}</button>
  );
}

// Each Counter has its own count, so the
// buttons don’t stay in sync.
export default function Counters() {
  return (
    <>
      <Counter />
      <Counter />
    </>
  );
}

Svelte with a shared module

counter.svelte.ts
// Every component that imports counter
// shares this one object.
export const counter = $state({ count: 0 });

// This doesn’t work. We can’t use a plain
// number. See “Why the Svelte module
// exports an object” below.
// export let counter = $state(0);
Counter.svelte
<script lang="ts">
  import { counter } from './counter.svelte.ts';
</script>

<button onclick={() => counter.count++}>
  {counter.count}
</button>
Counters.svelte
<script lang="ts">
  import Counter from './Counter.svelte';
</script>

<!-- Both buttons show the same count. -->
<Counter />
<Counter />

React with MobX

Click either button and both advance, because both read the same CounterStore instance. makeAutoObservable makes count observable and increment an action, and observer re-renders a component when an observable it read during render changes. Importing the store at module scope works like the Svelte module. MobX’s docs note that it can complicate testing and suggest providing the store through React context instead.

CounterStore.ts
import { makeAutoObservable } from 'mobx';

class CounterStore {
  count = 0;

  constructor() {
    makeAutoObservable(this);
  }

  increment() {
    this.count += 1;
  }
}

// One store, shared by every importer.
export const counter = new CounterStore();
Counters.tsx
import { observer } from 'mobx-react-lite';
import { counter } from './CounterStore';

const Counter = observer(function Counter() {
  'use no memo';
  return (
    <button onClick={() => counter.increment()}>
      {counter.count}
    </button>
  );
});

// Both buttons show the same count.
export default function Counters() {
  return (
    <>
      <Counter />
      <Counter />
    </>
  );
}

Worth knowing

Lift the count into the parent

Here Counters calls useCounter() once and passes count and increment to both buttons as props, so they share one count. The Hook itself is unchanged. Its state belongs to whichever component calls it, so moving the call up moved the owner.

The cost grows with the tree. Each click re-renders Counters and, by default, everything below it, as What Runs on Each Render shows. Every component between Counters and a button also has to accept the props and pass them on, the problem Context & Prop Drilling covers.

Counters.tsx
import { useCounter } from './useCounter';

function Counter({ count, onIncrement }: {
  count: number;
  onIncrement: () => void;
}) {
  return (
    <button onClick={onIncrement}>
      {count}
    </button>
  );
}

// Both buttons show the same count.
export default function Counters() {
  const { count, increment } = useCounter();
  return (
    <>
      <Counter count={count}
        onIncrement={increment} />
      <Counter count={count}
        onIncrement={increment} />
    </>
  );
}

Svelte’s version of a custom Hook

A function in a .svelte.ts module that creates $state does what a custom Hook does. Each component calls it once, as in const counter = createCounter(), and gets its own count, the same way each call to useCounter does. It isn’t bound by call order, so a condition or a loop around the call is fine.

Return a getter rather than the number. return { count } would copy the current value into a plain property, and so would destructuring the result, as in const { count } = createCounter(). It’s the rule from State & Reactivity: a value copied out of state stops updating. A class with $state fields does the same job, as the TaskList in Reducers & State Transitions shows.

createCounter.svelte.ts
// Shares the logic, not the state: each
// component that calls it gets its own count.
export function createCounter() {
  let count = $state(0);
  return {
    get count() {
      return count;
    },
    increment() {
      count++;
    },
  };
}

Why the Svelte module exports an object

A $state variable is reactive because the compiler rewrites every read and write of it, one file at a time. Another file that imported the variable would get the underlying signal instead of the number, so exporting a $state variable that the module reassigns is a compile error, state_invalid_export. If the module never reassigns it, export let counter = $state(0) compiles to a plain 0, and importers can’t change it because an import can’t be reassigned. An object carries its reactivity with it: $state({ count: 0 }) is a proxy that notifies on every property write, in any file. You can also keep the variable private and export functions that read and write it.

One count for the whole app

A MobX store created at module scope and a module-level $state object both hold one value for everyone who imports them. In the browser that’s one user. During server rendering the module is shared between requests, so one user’s state could appear on another user’s page. For state that belongs to one user or one part of the page, create it for each component tree and provide it through context, as in Context & Prop Drilling.

Application Patterns

Context & Prop Drilling

Follow a theme and its toggle through a layout that uses neither. Then choose who should own the theme and which readers should update.

The React prop-drilling problem

Some values are needed far from where they live. A theme, the signed-in user, or the current locale is usually owned near the top of the app and read by a component several layers down. With props alone, every component in between has to accept the value and pass it on, even if it never uses it. This is called prop drilling, or threading.

In the example, start at Dashboard and follow mode and onToggle to the button. Toolbar only arranges the layout, yet it has to accept both props, and giving the button one more value means editing its props too.

In a shallow tree like this one, drilling is often the clearest option. You can trace every value from its owner to its reader, and you can test the button by passing it two props. React’s docs recommend starting there. The cost grows with depth and with change. Renaming a prop or changing its shape ripples through every component on the way down. When a component stops needing a value, its parent may keep forwarding it, and an optional prop with a default can hide that a parent forgot to pass it.

Before reaching for context, look for a component that only forwards. If Dashboard builds the button itself and passes it to Toolbar as children, the props skip the middle entirely. Context is for values that many components at different depths need. A provider makes a value available to everything below it, and readers ask for it directly. The tradeoff is the one props avoided: the components in between no longer show where the value comes from.

Svelte passes props the same way, but its reactivity isn’t tied to components. A $state object exported from a .svelte.ts module stays reactive in any component that imports it, at any depth, so an app-wide value like this theme never has to travel through props. React state lives inside a component, so sharing it without props takes context or an external store. A module-level object is one instance for the whole app, though, so for values that belong to one user or one part of the page, Svelte uses context too, as the createContext example below shows.

Dashboard.tsx
import { useState } from 'react';

type Theme = 'light' | 'dark';
type ThemeProps = { mode: Theme; onToggle: () => void };

function Toolbar({ mode, onToggle }: ThemeProps) {
  // Toolbar only needs these props to pass them on.
  return <div><ThemeToggle mode={mode} onToggle={onToggle} /></div>;
}

function ThemeToggle({ mode, onToggle }: ThemeProps) {
  return (
    <button aria-pressed={mode === 'dark'} onClick={onToggle}>
      Dark mode
    </button>
  );
}

export default function Dashboard() {
  const [mode, setMode] = useState<Theme>('light');
  function toggle() {
    setMode(current => current === 'light' ? 'dark' : 'light');
  }

  return (
    <section>
      <p>Dashboard theme is {mode}.</p>
      <Toolbar mode={mode} onToggle={toggle} />
    </section>
  );
}

React with useContext

The dashboard provides the value and toggle function. The button reads them from the nearest provider, so each dashboard owns its own theme.

theme.ts
import { createContext } from 'react';

export type Theme = 'light' | 'dark';
type ThemeValue = { mode: Theme; toggle: () => void };
export const ThemeContext = createContext<ThemeValue | null>(null);
Dashboard.tsx
import { useState } from 'react';
import Toolbar from './Toolbar';
import { ThemeContext, type Theme } from './theme';

export default function Dashboard() {
  const [mode, setMode] = useState<Theme>('light');
  function toggle() {
    setMode(current => current === 'light' ? 'dark' : 'light');
  }

  return (
    <ThemeContext value={{ mode, toggle }}>
      <section>
        <p>Dashboard theme is {mode}.</p>
        <Toolbar />
      </section>
    </ThemeContext>
  );
}
Toolbar.tsx
import ThemeToggle from './ThemeToggle';

export default function Toolbar() {
  return <div><ThemeToggle /></div>;
}
ThemeToggle.tsx
import { useContext } from 'react';
import { ThemeContext } from './theme';

export default function ThemeToggle() {
  const theme = useContext(ThemeContext);
  if (!theme) throw new Error('Theme provider is missing');

  return (
    <button aria-pressed={theme.mode === 'dark'} onClick={theme.toggle}>
      Dark mode
    </button>
  );
}

Svelte with an imported $state object

Both readers import the same reactive object. Changing theme.mode updates the text and button together across dashboards in this browser app.

theme.svelte.ts
type Theme = 'light' | 'dark';
export const theme = $state<{ mode: Theme }>({ mode: 'light' });
Dashboard.svelte
<script lang="ts">
  import Toolbar from './Toolbar.svelte';
  import { theme } from './theme.svelte.ts';
</script>

<section>
  <p>Dashboard theme is {theme.mode}.</p>
  <Toolbar />
</section>
Toolbar.svelte
<script lang="ts">
  import ThemeToggle from './ThemeToggle.svelte';
</script>

<div><ThemeToggle /></div>
ThemeToggle.svelte
<script lang="ts">
  import { theme } from './theme.svelte.ts';

  function toggle() {
    theme.mode = theme.mode === 'light' ? 'dark' : 'light';
  }
</script>

<button aria-pressed={theme.mode === 'dark'} onclick={toggle}>
  Dark mode
</button>

Svelte with createContext

To give each dashboard its own theme, as the React provider does, create the reactive object inside each dashboard and set it as context during initialization. createContext returns typed accessors, which the module exports.

theme.ts
import { createContext } from 'svelte';

export type Theme = 'light' | 'dark';
export type ThemeState = { mode: Theme };
export const [getTheme, setTheme] = createContext<ThemeState>();
Dashboard.svelte
<script lang="ts">
  import Toolbar from './Toolbar.svelte';
  import { setTheme, type ThemeState } from './theme';

  const theme = $state<ThemeState>({ mode: 'light' });
  setTheme(theme);
</script>

<section>
  <p>Dashboard theme is {theme.mode}.</p>
  <Toolbar />
</section>
Toolbar.svelte
<script lang="ts">
  import ThemeToggle from './ThemeToggle.svelte';
</script>

<div><ThemeToggle /></div>
ThemeToggle.svelte
<script lang="ts">
  import { getTheme } from './theme';
  const theme = getTheme();

  function toggle() {
    theme.mode = theme.mode === 'light' ? 'dark' : 'light';
  }
</script>

<button aria-pressed={theme.mode === 'dark'} onclick={toggle}>
  Dark mode
</button>

React with MobX

Like the imported Svelte object, this store gives all dashboards one theme. Each observer component subscribes to the observable fields it reads during render. The toolbar stays plain. For one theme flag, React context has less setup. With many independently changing fields, that tracking can justify adding mobx, mobx-react-lite, and observer boundaries.

theme.ts
import { makeAutoObservable } from 'mobx';

class ThemeStore {
  mode: 'light' | 'dark' = 'light';

  constructor() {
    makeAutoObservable(this, {}, { autoBind: true });
  }

  toggle() {
    this.mode = this.mode === 'light' ? 'dark' : 'light';
  }
}

export const theme = new ThemeStore();
Dashboard.tsx
import { observer } from 'mobx-react-lite';
import { theme } from './theme';

const ThemeToggle = observer(function ThemeToggle() {
  'use no memo';
  return (
    <button aria-pressed={theme.mode === 'dark'} onClick={theme.toggle}>
      Dark mode
    </button>
  );
});

function Toolbar() {
  return <div><ThemeToggle /></div>;
}

export default observer(function Dashboard() {
  'use no memo';
  return (
    <section>
      <p>Dashboard theme is {theme.mode}.</p>
      <Toolbar />
    </section>
  );
});

State during server rendering. A module-level store can be shared across requests in both Svelte and MobX. For a user-specific theme, create fresh state for each rendered tree and provide it through context. In SvelteKit, the layout can initialize that state from data returned by its server load function.

Application Patterns

Reducers & State Transitions

A task list can add a task, toggle one, and clear finished tasks. Put those three changes in one place instead of spreading them across event handlers.

React

tasks.ts
export type Task = {
  id: number; title: string; done: boolean;
};
export type State = { tasks: Task[]; nextId: number };
export type Action =
  | { type: 'added'; title: string }
  | { type: 'toggled'; id: number }
  | { type: 'cleared' };

export function tasksReducer(
  state: State,
  action: Action
): State {
  switch (action.type) {
    case 'added': {
      const task: Task = {
        id: state.nextId, title: action.title, done: false,
      };
      return {
        tasks: [...state.tasks, task],
        nextId: task.id + 1,
      };
    }
    case 'toggled': {
      const toggle = (task: Task) => task.id === action.id
        ? { ...task, done: !task.done }
        : task;
      return { ...state, tasks: state.tasks.map(toggle) };
    }
    case 'cleared': {
      const tasks = state.tasks.filter(task => !task.done);
      return { ...state, tasks };
    }
  }
}
Tasks.tsx
import { useReducer, useState } from 'react';
import { tasksReducer } from './tasks';

export default function Tasks() {
  const [state, dispatch] =
    useReducer(tasksReducer, { tasks: [], nextId: 1 });
  const [title, setTitle] = useState('');

  function add() {
    dispatch({ type: 'added', title });
    setTitle('');
  }

  function toggle(id: number) {
    dispatch({ type: 'toggled', id });
  }

  function clearDone() {
    dispatch({ type: 'cleared' });
  }

  return (
    <>
      <input aria-label="New task" value={title}
        onChange={event => setTitle(event.target.value)} />
      <button onClick={add}>Add</button>
      <ul>
        {state.tasks.map(task => (
          <li key={task.id}>
            <label>
              <input type="checkbox" checked={task.done}
                onChange={() => toggle(task.id)} />
              {' '}{task.title}
            </label>
          </li>
        ))}
      </ul>
      <button onClick={clearDone}>Clear done</button>
    </>
  );
}

Svelte

tasks.svelte.ts
export type Task = {
  id: number; title: string; done: boolean;
};

export class TaskList {
  tasks = $state<Task[]>([]);
  #nextId = 1;

  add(title: string) {
    const id = this.#nextId++;
    this.tasks.push({ id, title, done: false });
  }

  toggle(id: number) {
    const task = this.tasks.find(item => item.id === id);
    if (task) task.done = !task.done;
  }

  clearDone() {
    this.tasks = this.tasks.filter(task => !task.done);
  }
}
Tasks.svelte
<script lang="ts">
  import { TaskList } from './tasks.svelte.ts';
  const list = new TaskList();
  let title = $state('');

  function add() {
    list.add(title);
    title = '';
  }
</script>

<input aria-label="New task" bind:value={title} />
<button onclick={add}>Add</button>
<ul>
  {#each list.tasks as task (task.id)}
    <li>
      <label>
        <input type="checkbox" checked={task.done}
          onchange={() => list.toggle(task.id)} />
        {task.title}
      </label>
    </li>
  {/each}
</ul>
<button onclick={() => list.clearDone()}>
  Clear done
</button>

Worth knowing

Keep the reducer pure

In development, Strict Mode calls each reducer twice to reveal side effects. That’s why nextId lives in state: a module-level counter incremented inside the reducer would skip numbers. Generate random IDs, timestamps, and requests in the event handler, then put the result in the action.

Dispatch through context

When distant components need to change the list, provide state and dispatch through context. Children dispatch named actions instead of receiving a callback for every operation. In Svelte, pass the TaskList instance through context to get the same effect.

Application Patterns

Window Events & the Document Head

An inbox panel closes when the reader presses Escape anywhere on the page, and the browser tab shows the unread count.

React

InboxPanel.tsx
import { useEffect, useEffectEvent } from 'react';

type Props = { unread: number; onClose: () => void };

export default function InboxPanel(
  { unread, onClose }: Props
) {
  const onKey = useEffectEvent((key: string) => {
    if (key === 'Escape') onClose();
  });

  useEffect(() => {
    function listener(event: KeyboardEvent) {
      onKey(event.key);
    }
    window.addEventListener('keydown', listener);
    return () => {
      window.removeEventListener('keydown', listener);
    };
  }, []);

  const title = unread > 0
    ? '(' + unread + ') Inbox'
    : 'Inbox';

  return (
    <section aria-label="Inbox">
      <title>{title}</title>
      <p>{unread} unread messages</p>
      <button onClick={onClose}>Close</button>
    </section>
  );
}

Svelte

InboxPanel.svelte
<script lang="ts">
  let { unread, onclose }: {
    unread: number;
    onclose: () => void;
  } = $props();

  let title = $derived(
    unread > 0 ? '(' + unread + ') Inbox' : 'Inbox'
  );

  function onkeydown(event: KeyboardEvent) {
    if (event.key === 'Escape') onclose();
  }
</script>

<svelte:window {onkeydown} />
<svelte:head>
  <title>{title}</title>
</svelte:head>

<section aria-label="Inbox">
  <p>{unread} unread messages</p>
  <button onclick={onclose}>Close</button>
</section>

Worth knowing

Metadata in a framework

The Next.js App Router prefers a metadata export or a generateMetadata function in page.tsx and layout.tsx, which it merges from the root layout down. SvelteKit pages use <svelte:head> for titles and meta tags, and the server-rendered HTML includes them. A title set inside a component suits client-side values like this unread count.

Application Patterns

External Stores & Browser APIs

Show a banner while the browser is offline. The value lives outside both frameworks, so each one subscribes to the browser’s online and offline events.

React

useOnline.ts
import { useSyncExternalStore } from 'react';

function subscribe(onChange: () => void) {
  window.addEventListener('online', onChange);
  window.addEventListener('offline', onChange);
  return () => {
    window.removeEventListener('online', onChange);
    window.removeEventListener('offline', onChange);
  };
}

export function useOnline() {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,
    () => true
  );
}
NetworkBanner.tsx
import { useOnline } from './useOnline';

export default function NetworkBanner() {
  const online = useOnline();
  return online ? null : (
    <p role="status">Offline: edits will sync later.</p>
  );
}

Svelte

network.ts
import { createSubscriber } from 'svelte/reactivity';

const subscribe = createSubscriber(update => {
  window.addEventListener('online', update);
  window.addEventListener('offline', update);
  return () => {
    window.removeEventListener('online', update);
    window.removeEventListener('offline', update);
  };
});

export const network = {
  get online() {
    subscribe();
    // Node's navigator has no onLine property
    return globalThis.navigator?.onLine ?? true;
  },
};
NetworkBanner.svelte
<script lang="ts">
  import { network } from './network';
</script>

{#if !network.online}
  <p role="status">Offline: edits will sync later.</p>
{/if}

Worth knowing

Why not useState and an Effect?

Copying navigator.onLine into state from an Effect works, but the first render shows the initial guess and the listener only starts after the browser paints. During a concurrent render, two components could also read different values of a changing store, which React calls tearing. useSyncExternalStore avoids both, and it’s how libraries such as Redux connect to React.

Ready-made reactive browser values

React has no built-in reactive browser values, so teams write small Hooks like useOnline or use a utility library. Svelte ships several: besides online, svelte/reactivity/window exports values such as innerWidth and scrollY, and new MediaQuery('(prefers-reduced-motion: reduce)') tracks a media query.

Application Patterns

Fetching & Race Conditions

Show the selected user’s name. Switch from user 1 to user 2 quickly, and a slow response for user 1 must not replace user 2.

users.ts
export type User = { name: string };

export async function loadUser(id: string, signal?: AbortSignal): Promise<User> {
  const response = await fetch('/api/users/' + encodeURIComponent(id), { signal });
  if (!response.ok) throw new Error('Could not load user (HTTP ' + response.status + ')');
  return response.json();
}

React

UserDetails.tsx
import { useEffect, useState } from 'react';
import { loadUser, type User } from './users';

type Result = {
  id: string; user?: User; failed?: boolean;
};

export default function UserDetails({ userId }: {
  userId: string;
}) {
  const [result, setResult] = useState<Result>();

  useEffect(() => {
    const controller = new AbortController();
    loadUser(userId, controller.signal)
      .then(
        user => ({ id: userId, user }),
        () => ({ id: userId, failed: true })
      )
      .then(next => {
        if (!controller.signal.aborted) setResult(next);
      });
    return () => controller.abort();
  }, [userId]);

  if (result?.id !== userId) {
    return <p role="status">Loading user…</p>;
  }
  if (result.failed) {
    return <p role="alert">Could not load user.</p>;
  }
  return <p>{result.user?.name}</p>;
}

Svelte

UserDetails.svelte
<script lang="ts">
  import { loadUser } from './users';
  let { userId }: { userId: string } = $props();
  let user = $derived(loadUser(userId));
</script>

{#await user}
  <p role="status">Loading user…</p>
{:then person}
  <p>{person.name}</p>
{:catch}
  <p role="alert">Could not load user.</p>
{/await}

Worth knowing

Most React apps don’t write this by hand

A hand-written Effect has no cache, so revisiting user 1 fetches again, and two components showing the same user make two requests. Framework loaders, Server Components, and data libraries such as TanStack Query handle caching, deduplication, and races for you. Keep Effects for small client-only fetches like this one.

The bug without cleanup

Remove the abort and the check, and the order of responses decides what appears. If user 1’s request takes 800 ms and user 2’s takes 100 ms, the page shows user 2 and then switches back to user 1. The same thing can happen in Svelte if an $effect assigns each response to $state without checking which request it belongs to.

Application Patterns

Pending UI & Suspense

Follow one click on “Load profile”. The button calls loadProfile() and passes its promise to the summary. While the request is pending, the summary shows “Loading profile…”. When the JSON arrives, it shows “Ada Lovelace”.

profile.ts
export type Profile = { name: string };

// Serve { "name": "Ada Lovelace" } at /profile.json.
export async function loadProfile(): Promise<Profile> {
  const response = await fetch('/profile.json');
  if (!response.ok) {
    throw new Error('Could not load profile (HTTP ' + response.status + ')');
  }
  return response.json();
}

React

ProfilePage.tsx
import { useState } from 'react';
import { loadProfile, type Profile } from './profile';
import ProfileSummary from './ProfileSummary';

export default function ProfilePage() {
  const [profile, setProfile] = useState<Promise<Profile> | null>(null);

  if (profile) return <ProfileSummary profile={profile} />;
  return <button onClick={() => setProfile(loadProfile())}>Load profile</button>;
}
ProfileSummary.tsx
import { Suspense, use } from 'react';
import type { Profile } from './profile';

type Props = { profile: Promise<Profile> };

function ProfileName({ profile }: Props) {
  const person = use(profile);
  return <p>{person.name}</p>;
}

export default function ProfileSummary({ profile }: Props) {
  return (
    <Suspense fallback={<p role="status">Loading profile…</p>}>
      <ProfileName profile={profile} />
    </Suspense>
  );
}

Svelte

ProfilePage.svelte
<script lang="ts">
  import { loadProfile, type Profile } from './profile';
  import ProfileSummary from './ProfileSummary.svelte';
  let profile = $state<Promise<Profile> | null>(null);
</script>

{#if profile}
  <ProfileSummary {profile} />
{:else}
  <button onclick={() => profile = loadProfile()}>Load profile</button>
{/if}
ProfileSummary.svelte
<script lang="ts">
  import type { Profile } from './profile';
  let { profile }: { profile: Promise<Profile> } = $props();
</script>

{#await profile}
  <p role="status">Loading profile…</p>
{:then person}
  <p>{person.name}</p>
{:catch}
  <p role="alert">Could not load profile.</p>
{/await}

Worth knowing

Never create the promise while rendering

use(loadProfile()) inside a component starts a new request on every render. When the request suspends, React later renders again, calls loadProfile() again, and receives yet another pending promise, so the fallback can stay forever. Create the promise in an event handler and store it, as this example does, or get it from a framework loader or data cache. Svelte’s {#await loadProfile()} in markup is safe because a template expression only re-runs when its reactive inputs change.

Svelte’s closest match to Suspense

ProfileSummary.svelte
<!-- With experimental.async enabled -->
<script lang="ts">
  import type { Profile } from './profile';
  let { profile }: {
    profile: Promise<Profile>;
  } = $props();
</script>

<svelte:boundary>
  <p>{(await profile).name}</p>
  {#snippet pending()}
    <p role="status">Loading profile…</p>
  {/snippet}
</svelte:boundary>

With the experimental.async compiler option, markup can await a promise directly. A <svelte:boundary> with a pending snippet then plays the part of Suspense: it shows its fallback when it first renders, until every await inside it has resolved, and a rejection goes to its failed snippet, as in Render Errors & Recovery. The option is still experimental in Svelte 5.59, so this lesson’s main example uses {#await}.

Application Patterns

Optimistic Updates & Rollback

Toggle a bookmark immediately. Both components receive a save function that returns the server’s confirmed boolean or rejects, and disable the button while saving.

React

Bookmark.tsx
import { useActionState, useOptimistic } from 'react';

type Result = { saved: boolean; error: string };
type Props = { save: (next: boolean) => Promise<boolean> };

export default function Bookmark({ save }: Props) {
  const [result, submit, pending] = useActionState(
    async (previous: Result): Promise<Result> => {
      const next = !previous.saved;
      show(next);
      try {
        return { saved: await save(next), error: '' };
      } catch {
        return { ...previous, error: 'Could not save bookmark.' };
      }
    },
    { saved: false, error: '' }
  );
  const [shown, show] = useOptimistic(result.saved);

  return (
    <form action={submit}>
      <button aria-pressed={shown} disabled={pending}>Bookmark</button>
      <p role="status">{pending ? 'Saving…' : result.error}</p>
    </form>
  );
}

Svelte

Bookmark.svelte
<script lang="ts">
  let { save }: { save: (next: boolean) => Promise<boolean> } = $props();
  let saved = $state(false);
  let shown = $derived(saved);
  let pending = $state(false);
  let error = $state('');

  async function toggle() {
    const next = !saved;
    pending = true;
    error = '';
    shown = next;
    try {
      saved = await save(next);
    } catch {
      error = 'Could not save bookmark.';
    } finally {
      shown = saved;
      pending = false;
    }
  }
</script>

<button aria-pressed={shown} disabled={pending} onclick={toggle}>Bookmark</button>
<p role="status">{pending ? 'Saving…' : error}</p>

React with MobX

Pass the same bookmark model to a toolbar and a detail view. Both show the prediction immediately, and the store’s pending guard prevents a second save through either control. After await, runInAction publishes the confirmed value, error, and pending flag together. React’s useOptimistic manages the temporary value for you. In MobX the store owns rollback, so every reader sees the same outcome.

BookmarkState.ts
import { makeAutoObservable, runInAction } from 'mobx';

export type Save = (next: boolean) => Promise<boolean>;

export class BookmarkState {
  saved = false;
  pending = false;
  error = '';

  constructor() { makeAutoObservable(this); }

  async toggle(save: Save) {
    if (this.pending) return;
    const previous = this.saved;
    this.saved = !previous;
    this.pending = true;
    this.error = '';

    let confirmed = previous;
    let error = '';
    try {
      confirmed = await save(this.saved);
    } catch {
      error = 'Could not save bookmark.';
    }
    runInAction(() => {
      this.saved = confirmed;
      this.error = error;
      this.pending = false;
    });
  }
}
Bookmark.tsx
import { observer } from 'mobx-react-lite';
import type {
  BookmarkState, Save
} from './BookmarkState';

type Props = {
  bookmark: BookmarkState;
  save: Save;
};

export default observer(function Bookmark(
  { bookmark, save }: Props
) {
  'use no memo';
  return (
    <>
      <button
        aria-pressed={bookmark.saved}
        disabled={bookmark.pending}
        onClick={() => void bookmark.toggle(save)}
      >
        Bookmark
      </button>
      <p role="status">
        {bookmark.pending ? 'Saving…' : bookmark.error}
      </p>
    </>
  );
});

Application Patterns

Render Errors & Recovery

Wrap a dashboard widget so a render failure leaves the rest of the dashboard usable. Let the reader retry the failed widget.

React

WidgetBoundary.tsx
import { Component, type ReactNode } from 'react';

export default class WidgetBoundary extends Component<
  { children: ReactNode }, { failed: boolean }
> {
  state = { failed: false };

  static getDerivedStateFromError() {
    return { failed: true };
  }

  render() {
    if (this.state.failed) {
      return (
        <>
          <p role="alert">Widget unavailable.</p>
          <button onClick={() => this.setState({ failed: false })}>
            Try again
          </button>
        </>
      );
    }
    return this.props.children;
  }
}

Svelte

WidgetBoundary.svelte
<script lang="ts">
  import type { Snippet } from 'svelte';
  let { children }: { children: Snippet } = $props();
</script>

<svelte:boundary>
  {@render children()}
  {#snippet failed(_error, reset)}
    <p role="alert">Widget unavailable.</p>
    <button onclick={reset}>Try again</button>
  {/snippet}
</svelte:boundary>

Worth knowing

What a boundary can’t catch

Both kinds of boundary catch errors thrown while their children render or run Effects. Neither catches an error in a click handler, a setTimeout callback, or a promise you await yourself, because that code runs outside rendering. Catch those where they happen and store the error in state if the UI should show it. React has two exceptions. A rejected promise read with use rethrows during render, so the boundary sees it. An error thrown inside an Action also reaches the nearest boundary, even after an await.

Report the error as well as showing it

In React, a boundary’s componentDidCatch(error, info) is where you send the error to your logging service, and info.componentStack shows where it happened. React 19 also accepts onCaughtError and onUncaughtError when you create the root, so one place can report every boundary’s errors. In Svelte, give <svelte:boundary> an onerror handler for the same job. In SvelteKit, the handleError hooks play the part of those root options, reporting errors from loading and rendering pages in one place.

DOM & Performance

Refs & DOM Access

Expose an input’s DOM node so its parent can move focus after a user action.

React

SearchFocus.tsx
import { useRef, type Ref } from 'react';

function SearchInput({ ref }: { ref: Ref<HTMLInputElement> }) {
  return <input aria-label="Search" ref={ref} />;
}

export default function SearchFocus() {
  const input = useRef<HTMLInputElement>(null);

  return (
    <>
      <button onClick={() => input.current?.focus()}>
        Focus search
      </button>
      <SearchInput ref={input} />
    </>
  );
}

Svelte

SearchInput.svelte
<script lang="ts">
  let { element = $bindable(null) }: {
    element?: HTMLInputElement | null;
  } = $props();
</script>

<input aria-label="Search" bind:this={element} />
SearchFocus.svelte
<script lang="ts">
  import SearchInput from './SearchInput.svelte';
  let input = $state<HTMLInputElement | null>(null);
</script>

<button onclick={() => input?.focus()}>Focus search</button>
<SearchInput bind:element={input} />

Worth knowing

Set up and clean up an element

To attach behavior such as a resize observer to one element, a React 19 ref callback can return a cleanup function. An inline callback is a new function on each render, so React detaches and reattaches it every time. Define it outside the component, wrap it in useCallback, or rely on React Compiler to keep it stable. React 19.3 also accepts a ref on <Fragment>, whose instance can focus, observe, or listen to the elements inside it without a wrapper element. Svelte’s {@attach} runs a function when the element mounts, re-runs it when its reactive reads change, and calls the cleanup it returns.

DOM & Performance

Portals & Dialogs

Show a toast from inside a card that clips its content with overflow: hidden. Render the toast at the end of document.body so the card can’t cut it off.

React

Toast.tsx
import { useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';

const subscribe = () => () => {};

export default function Toast({ message }: {
  message: string;
}) {
  // false on the server and while hydrating
  const inBrowser = useSyncExternalStore(
    subscribe, () => true, () => false
  );
  if (!inBrowser) return null;

  return createPortal(
    <div className="toast" role="status">{message}</div>,
    document.body
  );
}

Svelte

portal.ts
import type { Attachment } from 'svelte/attachments';

export function portal(target?: HTMLElement): Attachment {
  return node => {
    (target ?? document.body).append(node);
    return () => node.remove();
  };
}
Toast.svelte
<script lang="ts">
  import { portal } from './portal';
  let { message }: { message: string } = $props();
</script>

<div class="toast" role="status" {@attach portal()}>
  {message}
</div>

Worth knowing

For a modal, try <dialog> first

dialog.showModal() puts a dialog in the browser’s top layer, above every z-index and outside any clipping parent. It also makes the rest of the page inert and closes on Escape. Neither framework needs a portal for that. Get the element with bind:this or a ref, call showModal() from an event handler, and listen for close to update your state.

DOM & Performance

DOM Updates & Timing

Append a message, then scroll to the new bottom of a fixed-height log. Reading its height too early misses the row you just added.

React

MessageLog.tsx
import { useLayoutEffect, useRef, useState } from 'react';
import './message-log.css';

export default function MessageLog() {
  const [messages, setMessages] = useState<string[]>([]);
  const log = useRef<HTMLDivElement>(null);

  useLayoutEffect(() => {
    const node = log.current;
    if (node) node.scrollTop = node.scrollHeight;
  }, [messages.length]);

  function append() {
    setMessages(items => [...items, 'Message ' + (items.length + 1)]);
  }

  return (
    <>
      <button onClick={append}>Add message</button>
      <div role="log" aria-label="Messages" ref={log} className="message-log">
        {messages.map(message => <p key={message}>{message}</p>)}
      </div>
    </>
  );
}
message-log.css
.message-log {
  max-height: 6rem;
  overflow: auto;
}

Svelte

MessageLog.svelte
<script lang="ts">
  import { tick } from 'svelte';
  let messages = $state<string[]>([]);
  let log: HTMLDivElement;

  async function append() {
    messages.push('Message ' + (messages.length + 1));
    await tick();
    log.scrollTop = log.scrollHeight;
  }
</script>

<button onclick={append}>Add message</button>
<div role="log" aria-label="Messages" bind:this={log}
  style="max-height: 6rem; overflow: auto">
  {#each messages as message (message)}
    <p>{message}</p>
  {/each}
</div>

Worth knowing

React’s counterpart of tick()

MessageLog.tsx
// Inside the MessageLog component
function append() {
  flushSync(() => {
    setMessages(items => [
      ...items,
      'Message ' + (items.length + 1),
    ]);
  });
  // The new row is in the DOM now.
  const node = log.current!;
  node.scrollTop = node.scrollHeight;
}

flushSync from react-dom applies the update to the DOM before it returns, so the next line can read the new height, as await tick() does in Svelte. React’s guide to manipulating the DOM uses it to scroll to a newly added item. It forces a synchronous render, so use it sparingly.

Svelte’s counterpart of useLayoutEffect

MessageLog.svelte
// Inside MessageLog.svelte’s <script>
$effect(() => {
  // Reading the length subscribes to it.
  messages.length;
  log.scrollTop = log.scrollHeight;
});

Svelte’s $effect runs right after the DOM updates, before the browser paints, so it covers what useLayoutEffect does. Because it reads messages.length, the log scrolls whenever any code adds a message, and append no longer needs tick(). For work before the DOM changes, such as checking whether the reader was already at the bottom, use $effect.pre.

DOM & Performance

Responsive Input & Deferred Updates

Filter a long list while typing. Rendering the matches is slow, so keep the text field responsive and dim the results until they catch up.

React

Filter.tsx
import { useDeferredValue, useState } from 'react';
import SlowResults from './SlowResults';

export default function Filter() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const stale = query !== deferredQuery;

  return (
    <>
      <input aria-label="Filter" value={query}
        onChange={event => setQuery(event.target.value)} />
      <div style={{ opacity: stale ? 0.6 : 1 }}>
        <SlowResults query={deferredQuery} />
      </div>
    </>
  );
}
SlowResults.tsx
import { memo } from 'react';
import { items } from './items';

export default memo(function SlowResults({ query }: {
  query: string;
}) {
  const matches = items.filter(item =>
    item.includes(query)
  );
  return (
    <ul>
      {matches.map(item => <li key={item}>{item}</li>)}
    </ul>
  );
});

Svelte

Filter.svelte
<script lang="ts">
  import SlowResults from './SlowResults.svelte';
  let query = $state('');
  let applied = $state('');

  $effect(() => {
    const next = query;
    const id = setTimeout(() => applied = next, 200);
    return () => clearTimeout(id);
  });
</script>

<input aria-label="Filter" bind:value={query} />
<div style:opacity={query !== applied ? 0.6 : 1}>
  <SlowResults query={applied} />
</div>
SlowResults.svelte
<script lang="ts">
  import { items } from './items';
  let { query }: { query: string } = $props();
  let matches = $derived(
    items.filter(item => item.includes(query))
  );
</script>

<ul>
  {#each matches as item (item)}<li>{item}</li>{/each}
</ul>

Worth knowing

useTransition marks the update instead

When you own the state setter, wrapping its call in startTransition marks that update as non-urgent, and isPending from useTransition can show a spinner. Use useDeferredValue when the value arrives as a prop or when the same state also drives a text field. A controlled input’s own update can’t go in a transition, because each keystroke has to show up immediately.

Doing less work helps both

Deferring only changes when the slow render happens. If the list has thousands of rows, render fewer of them: cap the results, paginate, or use a virtualized list that only creates the rows on screen. That makes both versions faster, and it might let you drop the delay entirely.

DOM & Performance

Transitions & Visibility

Animate a panel entering and leaving the page with each framework’s built-in primitives.

React

Details.tsx
import { startTransition, useState, ViewTransition } from 'react';

export default function Details() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <button onClick={() => {
        startTransition(() => setOpen(value => !value));
      }}>
        Toggle details
      </button>
      {open && (
        <ViewTransition>
          <p>Details about the task.</p>
        </ViewTransition>
      )}
    </>
  );
}

Svelte

Details.svelte
<script lang="ts">
  import { fade } from 'svelte/transition';
  let open = $state(false);
</script>

<button onclick={() => open = !open}>Toggle details</button>

{#if open}
  <p transition:fade>Details about the task.</p>
{/if}

Worth knowing

Animating items that move

In React, wrap each keyed item in its own <ViewTransition>, and React plays an update animation when the order changes inside a transition. Leave out name, which is for shared-element transitions, and avoid a wrapper element between the list and the keyed items. An animation library is the other option. In Svelte, animate:flip on the items of a keyed {#each} slides each row from its old position to its new one. Either way, stable keys are what let the animation follow the right row.

DOM & Performance

Compiler & Memoization

Keep a component pure and let each framework optimize the work it can see.

Two compilers with different jobs

React Compiler makes each re-render do less. At build time it rewrites components to cache calculations and JSX, and reuses them while their inputs keep the same identity. That takes over most hand-written memoization: useMemo around a costly calculation, useCallback around a handler, and memo around a child. Before the compiler, caching this total by hand meant useMemo(() => items.reduce(…), [items]).

The Svelte compiler has no re-render to trim. It turns the template into code that updates each piece of the DOM that reads a reactive value, and $derived keeps the total until something it read changes. That’s the caching useMemo provides, without a dependency list.

React

Summary.tsx
type Item = { price: number };

// Correct with or without React Compiler.
export default function Summary({ items }: { items: Item[] }) {
  const total = items.reduce(
    (sum, item) => sum + item.price,
    0
  );

  return <p>Total: {total.toFixed(2)}</p>;
}

Svelte

Summary.svelte
<script lang="ts">
  type Item = { price: number };
  let { items }: { items: Item[] } = $props();
  let total = $derived(
    items.reduce((sum, item) => sum + item.price, 0)
  );
</script>

<p>Total: {total.toFixed(2)}</p>

React with MobX

Change a price in place. The cart keeps its identity, but the observed component read that item’s price during render, so MobX schedules an update. Each render still sums the items. A computed getter can share that sum across readers. In a React Compiler build, 'use no memo' keeps the compiler from caching the observer’s JSX, which would otherwise come back stale when MobX re-renders it. The mobx-react-plugin build plugin can insert the directive automatically when it runs before React Compiler.

Summary.tsx
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';

type Item = { price: number };

export class Cart {
  items: Item[];

  constructor(items: Item[]) {
    this.items = items;
    makeAutoObservable(this);
  }

  setPrice(index: number, price: number) {
    this.items[index].price = price;
  }
}

export default observer(function Summary({ cart }: {
  cart: Cart;
}) {
  'use no memo';
  const total = cart.items.reduce((sum, item) => sum + item.price, 0);
  return <p>Total: {total.toFixed(2)}</p>;
});

Framework Patterns: Next.js vs SvelteKit

Routes & Layouts

Add a /tasks section with shared navigation, a page for each task at /tasks/[id], and an error page for the section.

React · Next.js App Router

app/tasks/layout.tsx
import Link from 'next/link';
import type { ReactNode } from 'react';

export default function TasksLayout({ children }: {
  children: ReactNode;
}) {
  return (
    <>
      <nav><Link href="/tasks">All tasks</Link></nav>
      {children}
    </>
  );
}
app/tasks/[id]/page.tsx
export default async function TaskPage({ params }: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  return <h1>Task {id}</h1>;
}
app/tasks/error.tsx
'use client';

export default function TasksError({ error, retry }: {
  error: unknown;
  retry: () => void;
}) {
  const message = error instanceof Error
    ? error.message
    : 'Something went wrong.';
  return (
    <>
      <p role="alert">{message}</p>
      <button onClick={() => retry()}>Try again</button>
    </>
  );
}

SvelteKit

routes/tasks/+layout.svelte
<script lang="ts">
  import type { LayoutProps } from './$types';
  let { children }: LayoutProps = $props();
</script>

<nav><a href="/tasks">All tasks</a></nav>
{@render children()}
routes/tasks/[id]/+page.svelte
<script lang="ts">
  import { page } from '$app/state';
</script>

<h1>Task {page.params.id}</h1>
routes/tasks/+error.svelte
<script lang="ts">
  import { page } from '$app/state';
</script>

<p role="alert">{page.status}: {page.error?.message}</p>

Worth knowing

Find the matching file

page.tsx pairs with +page.svelte, layout.tsx with +layout.svelte, and error.tsx with +error.svelte. An API endpoint lives in route.ts in Next.js and +server.ts in SvelteKit. For a loading state, Next.js shows loading.tsx as a Suspense fallback, while SvelteKit streams a promise returned from load. Both use [id] for parameters and (group) folders to share a layout without changing the URL. In React Router, a route module with a loader and a default component plays the role of these files.

Same page, new parameter

Moving from /tasks/1 to /tasks/2 reuses the SvelteKit page component instead of creating a new one. Read page.params or data reactively, as this page does, because a value copied once in the script keeps the old id. Wrap the content in {#key page.params.id} if it should start fresh.

Framework Patterns: Next.js vs SvelteKit

Data Loading & Server Rendering

Both routes await the same database helper, listTasks, and pass its result to a Tasks component.

What stays on the server

Both frameworks render this page to HTML on the server, so the task list shows before any JavaScript runs. They split the rest of the work between server and browser in different places.

In the Next.js App Router the split runs between components. Components are Server Components by default, and 'use client' at the top of a file makes the components in it, and in every module it imports, Client Components. A Server Component such as TasksPage runs only on the server, so it can await listTasks() directly. A Client Component also renders on the server for the first HTML, then runs again in the browser, where it hydrates and responds to clicks.

SvelteKit splits at the load function instead. +page.server.ts runs only on the server, so it can await listTasks() directly. Every component, including +page.svelte and Tasks.svelte, works like a Client Component: it renders on the server for the first HTML, then hydrates in the browser. A universal +page.ts load runs on both the server and the browser, for data that needs no server-only access.

React · Next.js App Router

app/tasks/page.tsx
// Next.js App Router: a Server Component
import { listTasks } from '@/lib/tasks';
import Tasks from './Tasks';

export default async function TasksPage() {
  const tasks = await listTasks();
  return <Tasks tasks={tasks} />;
}

SvelteKit

+page.server.ts
import type { PageServerLoad } from './$types';
import { listTasks } from '#lib/server/tasks.ts';

export const load: PageServerLoad = async () => {
  return { tasks: await listTasks() };
};
+page.svelte
<script lang="ts">
  import Tasks from './Tasks.svelte';
  import type { PageProps } from './$types';
  let { data }: PageProps = $props();
</script>

<Tasks tasks={data.tasks} />

Framework Patterns: Next.js vs SvelteKit

Forms & Mutations

Show a pending button and return validation errors. Both examples call a project-specific subscribe function to save the email.

React · Next.js App Router

actions.ts
'use server';

import { subscribe } from '@/lib/newsletter';

export async function subscribeAction(
  _previous: { email: string; message: string },
  formData: FormData
) {
  const field = formData.get('email');
  const email = typeof field === 'string' ? field.trim() : '';
  if (!email.includes('@')) {
    return { email, message: 'Enter a valid email.' };
  }

  await subscribe(email);
  return { email: '', message: 'Subscribed.' };
}
Signup.tsx
'use client';

import { useActionState } from 'react';
import { subscribeAction } from './actions';

export default function Signup() {
  const [state, action, pending] =
    useActionState(subscribeAction, { email: '', message: '' });

  return (
    <form action={action}>
      <label>Email <input name="email" type="email"
        defaultValue={state.email} required /></label>
      <button disabled={pending}>
        {pending ? 'Subscribing…' : 'Subscribe'}
      </button>
      <p role="status">{state.message}</p>
    </form>
  );
}

SvelteKit

+page.server.ts
import { fail } from '@sveltejs/kit';
import type { Actions } from './$types';
import { subscribe } from '#lib/server/newsletter.ts';

export const actions = {
  default: async ({ request }) => {
    const field = (await request.formData()).get('email');
    const email = typeof field === 'string' ? field.trim() : '';
    if (!email.includes('@')) {
      return fail(400, { email, message: 'Enter a valid email.' });
    }

    await subscribe(email);
    return { email: '', message: 'Subscribed.' };
  },
} satisfies Actions;
+page.svelte
<script lang="ts">
  import { enhance } from '$app/forms';
  import type { PageProps, SubmitFunction } from './$types';
  let { form }: PageProps = $props();
  let pending = $state(false);

  const submit: SubmitFunction = () => {
    pending = true;
    return async ({ update }) => {
      try { await update(); }
      finally { pending = false; }
    };
  };
</script>

<form method="POST" use:enhance={submit}>
  <label>Email <input name="email" type="email"
    value={form?.email ?? ''} required /></label>
  <button disabled={pending}>{pending ? 'Subscribing…' : 'Subscribe'}</button>
  <p role="status">{form?.message}</p>
</form>

Worth knowing

Which form clears its fields?

After a form Action finishes without throwing, React 19 resets the form’s uncontrolled fields, including after a validation message. That’s why the React example returns the entered email and passes it back through defaultValue. The SvelteKit update() callback resets the form only when the action succeeds, so a failed submission keeps what the user typed. Pass update({ reset: false }) to keep values after a success too.

Who refreshes the data afterward?

In Next.js, call revalidatePath or a tag-based equivalent inside the Server Function. That marks cached Server Component output as stale so the page receives the new list. After a successful enhanced submission, SvelteKit calls refreshAll(), formerly invalidateAll(), so every load function on the page and any active remote query runs again. Pass update({ refreshAll: false }) to skip it. Without JavaScript, the POST response renders the page with fresh data.

Reference

Quick Reference

Find a pattern in either framework and jump to its side-by-side example.

Task React Svelte
Write a componentA function that returns JSX A .svelte file with $props and $state
Update local stateuseState setter or updater $state assignment
Know what runs after a state changeThe component function and its children Reactive reads; <script> runs once
Derive a filtered listCalculate during render MobX · A computed getter on the search model$derived
Synchronize with an external systemuseEffect with dependencies and cleanup $effect
Write attributes, events, and conditionsclassName, htmlFor, onClick, && or a ternary HTML names, onclick, class:, {#if}
Render keyed itemsitems.map() with a key prop MobX · An observer for the list and one for each row{#each items as item (item.id)}
Pass customizable contentchildren or a render prop children or a parameterized snippet
Let a parent control a text fieldvalue + onChange $bindable + bind:value
Reuse a styled componentBadge.tsx with className and badge.css Badge.svelte with a scoped <style> block
Type a component over any itemfunction Picker<T>(props: Props<T>) <script generics="T">
Share state between componentsLift state to a common parent, or use a store such as MobX MobX · One store instance that every reader importsExport a $state object from a .svelte.ts module
Reuse stateful logicA custom Hook A function in a .svelte.ts module that creates $state
Share state with distant descendantsuseContext per provider MobX · Observers subscribe to fields on a shared theme storeImported $state for one instance, context per subtree
Name every change to related stateuseReducer with typed actions A class with $state fields and methods
Listen to the window and set the titleuseEffect listener and <title> in the tree <svelte:window> and <svelte:head>
Subscribe to a browser APIuseSyncExternalStore createSubscriber inside a getter
Fetch when a prop changesuseEffect with AbortController cleanup $derived promise + {#await}
Show a fallback for a pending promiseuse(promise) under Suspense {#await} and {:then}
Show a save before it is confirmeduseOptimistic inside an Action MobX · An optimistic store action with explicit rollbackTemporarily override $derived
Recover from a failing widgetError boundary with a fallback and retry <svelte:boundary> with failed + reset
Focus a child’s inputuseRef + a ref prop bind:this + a bindable prop
Render outside the parent’s DOMcreatePortal(children, document.body) An attachment that moves the node
Read the DOM after appending a rowuseLayoutEffect after commit await tick()
Keep typing smooth during a slow renderuseDeferredValue + memo A debounced $effect timer
Animate entry and exit<ViewTransition> around the element + startTransition transition:fade on the element
Optimize renderingReact Compiler or measured memoization MobX · Runtime tracking inside an observerSvelte compiler and reactive dependencies
Add a route with a shared layoutlayout.tsx and page.tsx +layout.svelte and +page.svelte
Load route dataNext.js async Server Component or React Router loader SvelteKit server load
Submit a server mutationNext.js Server Function + useActionState SvelteKit page action + use:enhance
Updated November 29, 2026