Svelte - 102

Reactive Values

this is something we want to compute every time component mounts

Svelte automatically updates the DOM when your component's state changes. Often, some parts of a component's state need to be computed from other parts (such as a fullname derived from a firstname and a lastname), and recomputed whenever they change.

For these, we have reactive declarations.

<script>
  // reactive declaration
  $: foo = bar;
  // reactive statement
  $: {
      something = somethingElse;
  }
</script>

Very interesting Concept in svelte

Declaration

  • reactive declaration is a variable which is dependent on other variables

  • every time the value of declaration will be computed and changed when count is changed

<script>
  let count = 0;
  $: doubled = count * 2;
</script>

doubled is reactive variable

when ever count changes , svelte will compute the value of doubled

reactive declartions can also depend on other reactive variables

$: quadrupled = doubled * 2

Reactive Statements

  • its a block which re-runs when dependency changes
<script>
  let count = 0;
  let prevCount = 0;
  let countWentUp = false;
  // Simple statement
  $: console.log('Count is' + count);

// Block statement
  $: {
      countWentUp = prevCount < count;
      prevCount = count;
  }
</script>

Order of execution of reactive statements

<script>
  let count = 0;
  $: quadrupled = doubled * 2; // runs 2nd
  $: doubled = count * 2; // runs 1st
  $: console.log(quadrupled); // runs 3rd
  $: console.log(count); // runs last
</script>
  • order depends on variables and dependencies

  • if there's no dep then it will execute as we have written

  • in above example, which statement directly depends on count ?

  • its doubled so it will run first, doubled is dep in quadrupled and so on

<script>
  let count = 0;
  let multiplyBy = 2;

  $: multiplied = multiply(count);

  function multiply(value) {
      return value * multiplyBy;
  }
</script>

one more intersting usecase

the order depends on direct dependencies

like in multiplied statement we have direct dep count , so it will only run when there is change in count but also we have multiplyBy dependency in function , yes we have , but again it wont effect the reactive statement

by chance we want to run our reactive statement when we have any change in multiplyBy

for that we can write it like this

<script>
  // ...
  $: variableWhichShouldTriggerRecalculation, retriggerCalculation();
  // ...
</script>

Reactive statements runs only once for performance and saving us from endless loops

when to use reactive statements and declarations ? when we want to run something on every state change, when there is related dependency

and remembers -> declarations means declaring something ($ a = b)

statement means (console.log())

here this blog ends -> svelte is awesome -> a great tool to explore
https://learn.svelte.dev/tutorial/reactive-declarations