Skip to content

How does $effect detect which variables to watch? #16579

@louisabraham

Description

@louisabraham

Describe the bug

<script>
  let count = $state(0);
  let flag = false;
  function handleClick() {
    count += 1;
    console.log("flag is", flag);
    flag = true;
  }

  $effect(() => {
    console.log("effect");
    if (flag) console.log(count);
  });
</script>

<button onclick={handleClick}>
  Count is {count}
</button>

Clicking a few times on the button outputs

effect
flag is false
flag is true
flag is true
flag is true

Adding an empty nil in the effect works (it actually calls the effect):

<script>
  let count = $state(0);
  let flag = false;
  function handleClick() {
    count += 1;
    console.log("flag is", flag);
    flag = true;
  }
	
  let nil = (...args) => {};
  $effect(() => {
    nil(count);
    console.log("effect");
    if (flag) console.log(count);
  });
</script>

<button onclick={handleClick}>
  Count is {count}
</button>

playground

it looks like the first evaluation basically tells svelte that flag is false and that it should ignore the rest of the code. Alternatively, converting flag to $state works. But I think it is not clear from the docs that $effect won't catch the dependency on count if it is in a branch.

Reproduction

see above

Logs

System Info

playground

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions