Consider this Svelte component using a derived value with $:
<script>
let count = 2;
$: doubled = count * 2;
</script>
<button on:click={() => count++}>Increment</button>
<p>Doubled: {doubled}</p>What will be shown in the paragraph after clicking the button 3 times?
<script>
let count = 2;
$: doubled = count * 2;
</script>
<button on:click={() => count++}>Increment</button>
<p>Doubled: {doubled}</p>Remember the initial count and how many times it increments.
The initial count is 2. Clicking 3 times increments count to 5. The derived value doubled is 5 * 2 = 10 (option D).
Given this Svelte code:
<script>
let firstName = 'Jane';
let lastName = 'Doe';
$: fullName = `${firstName} ${lastName}`;
</script>
<button on:click={() => lastName = 'Smith'}>Change Last Name</button>
<p>Full Name: {fullName}</p>What will be displayed after clicking the button once?
<script>
let firstName = 'Jane';
let lastName = 'Doe';
$: fullName = `${firstName} ${lastName}`;
</script>
<button on:click={() => lastName = 'Smith'}>Change Last Name</button>
<p>Full Name: {fullName}</p>Derived values update automatically when dependencies change.
When lastName changes to 'Smith', the derived fullName updates to 'Jane Smith'.
Which of these code snippets correctly uses the $: syntax to create a derived value?
The $: label is used before the statement without let.
Option B correctly uses $: to declare a reactive statement. Options B, C, and D have invalid syntax.
Look at this Svelte code:
<script>
let a = 1;
let b = 2;
$: sum = a + b;
function updateA() {
a = a + 1;
}
</script>
<button on:click={updateA}>Update A</button>
<p>Sum: {sum}</p>After clicking the button, the sum does not update. What is the likely cause?
<script>
let a = 1;
let b = 2;
$: sum = a + b;
function updateA() {
a = a + 1;
}
</script>
<button on:click={updateA}>Update A</button>
<p>Sum: {sum}</p>Check how Svelte tracks reactive variables and updates.
Variables declared with 'let' are reactive. Changing 'a' triggers the derived value 'sum' to update. The sum updates correctly.
Which statement best describes the difference between Svelte's $: reactive statements and React's useMemo hook?
Think about how dependencies are declared and tracked in both.
Svelte's $: reactive statements automatically track all variables used inside them. React's useMemo requires you to list dependencies explicitly in an array.