| | |

Svelte 10 ๐Ÿงก Un-proxied Shallow State using $state.raw()

โฑ๏ธ Estimated read: 7 min | |

In Svelte, the $state() rune provides powerful deep reactivity by wrapping data in proxies that track every read and write. While this is ideal for most UI state, there are scenarios where proxying is either unnecessary or actively harmful. Large data sets, deeply nested static configurations, or third-party libraries that rely on internal object structure can be hindered by the overhead of Svelteโ€™s reactivity system. This is where $state.raw() comes in. It allows you to hold data in a Svelte-managed state container without the performance cost or behavioral overhead of reactive proxies.

$state.raw() treats data as a black box. The framework holds a reference to the data, but it does not intercept property access or modifications. This means that while you can swap out the entire raw object to trigger an update, individual changes to properties within that object will not cause the UI to re-render. This chapter examines when to bypass proxies, how to manage un-proxied state, and why this primitive is essential for high-performance Svelte applications.

Key point: $state.raw() stores data without creating proxies, meaning changes to the contents of the object or array do not track, but reassigning the container itself still triggers updates.


Why exists

The proxy-overhead problem. For massive data structures like geospatial points, large JSON dictionaries, or scientific data sets, proxying every single node consumes significant memory and CPU cycles during initialization.

The library compatibility constraint. Many third-party libraries, such as complex visualization engines (D3, Three.js) or state-heavy editors (Monaco), utilize internal symbols, getters, or prototype methods that conflict with Svelteโ€™s proxy-based interception.

The static data requirement. In large-scale applications, you often have read-only configuration objects or static assets that never change. Converting these to reactive proxies is redundant work that adds no value to the user.

The performance trade-off. Proxying is not free; every access is an extra layer of code execution. $state.raw() allows developers to opt-out of reactivity for performance-critical segments of the state tree.

The intentional immutability pattern. By using $state.raw(), you force yourself into an immutable pattern. You cannot rely on mutation-based updates; you must replace the container, which can lead to safer and more predictable architecture for complex domain models.


a. Understanding Shallow Reactivity

Unlike $state(), which performs recursive traversal to wrap every child in a proxy, $state.raw() creates a shallow container. It stores the provided value exactly as it is, without modification. This is why it is often called “un-proxied” state.

let config = $state.raw({ 
  theme: "dark", 
  version: 1.0 
});

// Changing a property does nothing to the UI
config.theme = "light"; 

// Reassigning the container triggers an update
function refresh() {
  config = { ...config, theme: "light" };
}

Because Svelte does not have access to the internals of the config object, it only observes the assignment to the variable config itself. This makes it an ideal candidate for objects that should be treated as immutable blobs.

b. Working with Third-Party Integrations

When integrating with external libraries, proxies can cause “identity” issues where the object returned by the library no longer behaves like the object Svelte is holding. Using $state.raw() allows the library to work with the plain, non-proxied object directly.

// Third-party charting library
import { Chart } from 'chart-library';

let chartData = $state.raw(massiveDataArray);

$effect(() => {
  const chart = new Chart(element, chartData);
  return () => chart.destroy();
});

By wrapping the data in $state.raw(), you ensure that Svelte maintains the reference for your component lifecycle while the library enjoys raw access to the data structure without the interference of proxy getters.

c. The Reassignment Trigger

Since $state.raw() does not track mutations, the only way to notify Svelte that your data has changed is to reassign the variable. This encourages developers to use standard functional patterns like spread operators or Object.assign to prepare new versions of the state before applying them.

let list = $state.raw([1, 2, 3]);

function add(item: number) {
  // We must create a new reference to trigger reactivity
  list = [...list, item];
}

This makes the flow of data very explicit. Any component consuming list will know exactly when it has been updated, because the reference identity of list changes on every update.


Complete Example Session

// ============================================
// PART 1: DECLARING RAW STATE
// ============================================
let data = $state.raw({ items: [] });

// ============================================
// PART 2: ATTEMPTING MUTATION (NO UI UPDATE)
// ============================================
function updateProp() {
  data.items.push(1); // The array updates in memory, but UI stays static
}

// ============================================
// PART 3: TRIGGERING UPDATE VIA REASSIGNMENT
// ============================================
function triggerUpdate() {
  data = { items: [...data.items, 1] }; // UI updates here
}

// ============================================
// PART 4: INTEGRATING WITH LIB
// ============================================
let heavyLibInstance = $state.raw(new ExpensiveLibrary());

// ============================================
// PART 5: SHARED STATIC CONFIG
// ============================================
export const APP_CONFIG = $state.raw({ version: '1.0.0' });

// ============================================
// PART 6: COMPARING $state VS $state.raw
// ============================================
let reactive = $state({ val: 0 }); // changes auto-track
let raw = $state.raw({ val: 0 });  // changes ignore

// ============================================
// PART 7: ARRAY HANDLING
// ============================================
let rawArr = $state.raw([]);
rawArr = [...rawArr, 'new'];

// ============================================
// PART 8: CONDITIONAL REASSIGNMENT
// ============================================
if (needsUpdate) {
  data = { ...data, items: [1, 2] };
}

// ============================================
// PART 9: DERIVING FROM RAW
// ============================================
let count = $derived(data.items.length);

// ============================================
// PART 10: CLEANING UP
// ============================================
// No proxies to clean up, simply reset reference
data = { items: [] };

These parts highlight that $state.raw() moves the update responsibility from the Proxy engine to the developer, requiring explicit assignment for reactivity.


Quick Reference

Comparison Table

Feature$state()$state.raw()
ProxyingDeep (Recursive)None (Shallow)
UI UpdateAutomatic mutationExplicit reassignment
PerformanceHigher memory/CPULower memory/CPU
UsageUI StateStatic/Lib/Large data

Triggering Updates

Method$state()$state.raw()
obj.x = 1YesNo
arr.push()YesNo
obj = { ... }YesYes

Best Practices

โœ… Do This:

let config = $state.raw(staticConfig);                        // โœ… Use for static data
let lib = $state.raw(new HeavyLibrary());                     // โœ… Use for 3rd party libs
data = { ...data, newProp: 'val' };                           // โœ… Update via assignment
let arr = $state.raw([]); arr = [...arr, 1];                  // โœ… Use immutable patterns

โŒ Don’t Do This:

let count = $state.raw(0); count++;                           // โŒ Won't trigger UI
let data = $state.raw({ nested: { x: 1 } });                  // โŒ Deep mutations fail
let user = $state.raw({ name: "Alice" }); user.name = "Bob";  // โŒ Won't trigger UI

Common Pitfalls

PitfallWhy It HappensFix
UI staleMutation without reassignReassign variable
Proxy shockConfusing raw with proxyUse $state() for UI logic
Wrong primitiveAccidental raw usageSwitch to $state()
Lost updatesThinking mutation worksExplicitly spread state

Real-World Examples

1. Large JSON Dataset

let bigData = $state.raw(fetchFromAPI());

2. D3 Chart Instance

let chart = $state.raw(new D3Chart(selector));

3. Editor Instance (Monaco)

let editor = $state.raw(monaco.create(el));

4. Game Configuration

let gameRules = $state.raw(deeplyNestedStaticJson);

5. Immutable State Container

let state = $state.raw({ clicks: 0 });
state = { clicks: state.clicks + 1 };

6. Large Map/Set

let registry = $state.raw(new Map());
registry = new Map(registry.set(key, val));

7. Read-only Reference

let assets = $state.raw(loadStaticAssets());

8. Canvas Context

let ctx = $state.raw(canvas.getContext('2d'));

9. Static Localization Keys

let i18n = $state.raw(loadLocale());

10. Placeholder for DI

let service = $state.raw(new Service());

Visual

Proxy Boundary

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  $state()                                    โ”‚
โ”‚  [Wrapper] โ”€โ”€โ–บ [Proxy] โ”€โ”€โ–บ [Object]          โ”‚
โ”‚  Tracks every detail automatically           โ”‚
โ”‚                                              โ”‚
โ”‚  $state.raw()                                โ”‚
โ”‚  [Wrapper] โ”€โ”€โ–บ [Object]                      โ”‚
โ”‚  No tracking, explicit updates only          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Reassignment Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  RAW STATE REFRESH                           โ”‚
โ”‚  1. Current: { val: 1 }                      โ”‚
โ”‚  2. Mutation: val becomes 2 (Ignore)         โ”‚
โ”‚  3. Reassign: data = { val: 2 }              โ”‚
โ”‚  4. UI Notify: Re-render                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Library Integration

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Library (e.g. Three.js)                     โ”‚
โ”‚  Expects clean object                        โ”‚
โ”‚        โ–ฒ                                     โ”‚
โ”‚        โ”‚                                     โ”‚
โ”‚  $state.raw() container                      โ”‚
โ”‚  Holds pure object                           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
MechanismShallow reference
ProxyNone
Update strategyImmutable/Reassignment
PerformanceHigh
Best forLarge data, Libs, Config

Key takeaways:

  • $state.raw() bypasses proxies. By skipping the proxy layer, you improve performance and avoid compatibility issues with external libraries.
  • Mutations are ignored. If you modify properties inside an object stored in $state.raw(), the UI will not update.
  • Assignment is mandatory. The only way to trigger an update for raw state is to assign a new value to the variable.
  • Use for static or non-UI data. If you don’t need the UI to react to internal object changes, $state.raw() is the correct tool.
  • Combine with functional patterns. Since you must assign new values, raw state pairs perfectly with spreading ... and other immutable JS patterns.

Remember: $state.raw() is an essential tool in the Svelte developer’s performance toolkit. It represents the “escape hatch” from the auto-proxied reactive world, allowing you to explicitly control when updates happen. By choosing this over $state(), you signal to the framework that you are taking manual responsibility for synchronization, which can lead to cleaner, more efficient, and library-compatible component logic.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!