Reactivity Optimization
Use $state Sparingly
Only make variables reactive when necessary:
Choose Between $state and $state.raw
For large objects that are only reassigned (not mutated), use $state.raw:
$state.raw when:
- Working with large API responses
- Data is replaced wholesale, not mutated
- Objects are frequently reassigned
$state when:
- Mutating nested properties (
user.name = 'Alice') - Need fine-grained reactivity
- Working with small objects
Prefer $derived over $effect
Compute values with $derived, not $effect:
$derived is more efficient and clearer than $effect for computing values from state.Avoid Reactive Statement Overhead
In legacy mode, reactive statements ($:) run more often than necessary:
Rendering Optimization
Use Keyed Each Blocks
Always provide keys in{#each} blocks for efficient updates:
- Without key: O(n) - Updates all existing DOM nodes
- With key: O(log n) - Moves/inserts/removes specific nodes
1
item.id, not array indexAvoid Index as Key
Minimize Component Re-renders
Prevent unnecessary work by isolating reactive dependencies:Component Design Patterns
Extract Expensive Logic
Move expensive computations to dedicated components:Use Event Delegation
For many similar elements, use event delegation:Avoid Inline Object/Array Creation
Bundle Size Optimization
Code Splitting with Dynamic Imports
Lazy load components that aren’t immediately needed:Tree Shaking
Import only what you need:Analyze Bundle Size
Use tools to find optimization opportunities:Advanced Optimizations
Virtual Lists for Large Datasets
For thousands of items, render only visible rows:Debounce Expensive Operations
Memoize Complex Computations
Image and Asset Optimization
Lazy Load Images
Use Modern Formats
Profiling and Measurement
Use Browser DevTools
1
Use $inspect.trace
Debug reactive dependencies:
Best Practices Checklist
1
{#each} blocks for all lists$state for constants - use plain variables$derived over $effect for computed values$state.raw for large objects that are only reassigned