Skip to content

Study Journal 05-08-2024

Published: at 12:00 AM

Where I’m at

What I learnt

Svelte 5 Runes

As explained below: Svelte 5 Runes Diagram

I thought that a great way of remembering this was to create a heurisitic as a way to guide me through creating a Rune correctly. This is what I came up with:

A Runes Heuristic: SOLID Creation Checklist

When creating a Rune, ask yourself:

Remember: If it’s read, it’s a dependency!

To illustrate in more detail, here’s each principle:

  1. Sources: Identify all the primary data sources (i.e $state variables) that your Rune uses.
  2. Operations: Consider all the operations performed on these sources. Each operation could introduce a dependency.
  3. Logic: If there is conditional logic to the Runes, then you have to make sure that all branches are accounted for in your dependencies. Basically making sure you look downstream.
  4. Indirect Dependencies: If your Rune uses derived values, remember that it indirectly depends on their dependencies too. This is the opposite of #3 — you’re now looking upstream.
  5. Dynamic Dependencies: In some cases, the dependencies themselves might change based on conditions. Be aware of these scenarios. This is usually when the rune $effect is used, and any side effects should be carefully considered so to not create an unforeseen dependancy.

It’s useful to reiterate the key here: “If it’s read, it’s a dependency!” Meaning any value that the Rune reads or uses in any way should be considered a dependency.

Here’s an example:

const price = $state(10);
const quantity = $state(2);
const discountRate = $state(0.1);
const isVIP = $state(false);

const totalCost = $derived(() => {
  // S: price, quantity, discountRate, isVIP
  // O: multiplication, conditional subtraction
  // L: condition for VIP discount
  // I: none in this case
  // D: discount application depends on isVIP

  const basePrice = price * quantity;
  if (isVIP) {
    return basePrice - (basePrice * discountRate);
  }
  return basePrice;
});

In general

What I did

Consider supporting this blog