svelte: Bad state in effect teardowns ; non-nullable props are sometimes null

Update

It’s better to read this comment explaining everything, rather than sift through this entire issue + thread.

Describe the bug

In short:

let thing = $state(true)

// no longer true!!
thing = false

// later
if (thing) doSomething() // this executes, but it shouldn't

Initially my code had let thing = true. I want to expose the state for use in UI in a template (so I change it to use $state), but this breaks the existing code, as for whatever reason getting the variable returns true even after it’s set to false.

Reproduction

https://svelte.dev/playground/f81b82a8cefd45da95d8301e82b0d5d4?version=5.33.4

Update: Better repro - https://svelte.dev/playground/a8c378e462544c9baf1b5f22e0531185?version=5.33.4

Severity

important

Workaround

Currently I use:

let thing = false
let thing2 = $state(false)

function setThing(value) {
  thing = value
  thing2 = value
}

// code keeps using non-reactive state, so it works
if (thing) doSomething()

// in template, where reactivity is needed, use thing2

This is much less than ideal

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 21 (16 by maintainers)

Most upvoted comments

Hi, @tfedor. I started creating a PR to fix this issue (and yours), but it turns out your issue is actually a different bug, so I created #16148 explaining it, if you want to follow it.

Update: Made a PR to fix the issue, you can try your REPL with this PR by changing the version query parameter to pr-16150 in the URL