Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bound elements should probably not be reactive on write #6521

Closed
nolanlawson opened this issue Jul 13, 2021 · 1 comment
Closed

Bound elements should probably not be reactive on write #6521

nolanlawson opened this issue Jul 13, 2021 · 1 comment

Comments

@nolanlawson
Copy link
Contributor

Describe the bug

This bug is a longwinded way to argue that something like this:

<script>
  let element
  $: {
    element.scrollTop = 0
  }
</script>
<div bind:this={element}></div>

...should probably not result in element being invalidated on the "write" to scrollTop. (Or alternatively, there should be a way to opt-out of the reactivity.)

I recently ran into an infinite loop that I accidentally triggered using some code like the following:

requestAnimationFrame(() => {
  if (element) {
    element.scrollTop = 0
  }
})

The problem is that this turns into:

if ($$self.$$.dirty & /*element*/ 3) {
  $: {
    requestAnimationFrame(() => {
      if (element) {
        $$invalidate(1, element.scrollTop = 0, element);
      }
    }
  }
}

So the infinite loop happens because it's "reading" element in the if (element) block, then "writing" to the element in the element.scrollTop = 0 part. So it calls rAF over and over again.

I found this surprising, because it didn't occur to me that elements bound with bind:this= would be reactive on "write" like this.

That said, it probably does need to be reactive on "read," since the element may or may not exist, and I imagine people are using if (element) to check for that.

Reproduction

Repro in the REPL

Click the "increment" button, and then notice that you can't scroll the scrollable <div> anymore. You can also use the Performance profiler in DevTools to see that it's constantly running an infinite requestAnimationFrame loop.

Logs

No response

System Info

N/A, occurs in all browsers

Severity

annoyance

@nolanlawson
Copy link
Contributor Author

Just occurred to me that this doesn't make much sense, because you need the full reactivity for something like:

$: {
  if (element.scrollTop > 0) {
    element.scrollTop = 0
  }
}

So maybe this just comes down to general footguns with reactivity, and being aware of them as a developer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant