Performance: Auto-subscription with $ prefix
This affects how reactive updates trigger DOM changes and browser rendering performance.
import { writable } from 'svelte/store'; const count = writable(0); // In component template or script // Use $count directly to auto-subscribe and update UI reactively <p>{$count}</p>
import { writable } from 'svelte/store'; const count = writable(0); let currentCount; const unsubscribe = count.subscribe(value => { currentCount = value; // manually update UI or trigger re-render }); // Use currentCount in template // Remember to unsubscribe when no longer needed // unsubscribe();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual subscription with subscribe() | Multiple DOM writes if not batched | Multiple reflows per update | Higher paint cost due to repeated updates | [X] Bad |
| Auto-subscription with $ prefix | Single DOM write per reactive change | Single reflow per update | Lower paint cost due to efficient batching | [OK] Good |
$ prefix do when used with a Svelte store inside a component?$ prefix$ prefix in Svelte is used to auto-subscribe to a store and unwrap its current value.$store makes the component update automatically when the store value changes, without manual subscription.$ prefix with a Svelte store named count inside a component?$ prefix is placed directly before the store variable name to unwrap its value, like $count.let value = $count; uses let value = $count; which is valid syntax to get the current store value reactively.let value = $count; [OK]count.update(n => n + 1)}>IncrementCount: {$count}
count starts at 0. Each button click increases it by 1 using count.update(n => n + 1).{$count} auto-subscribes and shows the current value.$ prefix?Hello, {currentName}!
name.set('Bob')}>Change Name
currentName is assigned the store itself, not its value. To get the current value reactively, it should be let currentName = $name;.$, currentName is the store object, so the UI shows it incorrectly and does not update on changes.currentName should use $name to auto-subscribe. [OK]countA and countB. You want to display their sum reactively in a component. Which is the correct way to do this using the $ prefix?Sum: ???
$countA and $countB unwraps their current values reactively.$countA + $countB inside curly braces calculates the sum reactively and updates UI on changes.<p>Sum: {$countA + $countB}</p> [OK]Pass the test and this pattern moves unknown