Skip to content

Non-updated state treated differently in different places #14280

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

Closed
Rich-Harris opened this issue Nov 12, 2024 · 3 comments · Fixed by #15781
Closed

Non-updated state treated differently in different places #14280

Rich-Harris opened this issue Nov 12, 2024 · 3 comments · Fixed by #15781

Comments

@Rich-Harris
Copy link
Member

Describe the bug

Minor, but given a component like this...

<script>
  let a = $state(1);
  let b = $state(2);
</script>

<p>{a} + {b} = {a + b}</p>

...neither a nor b is turned into state, because they are never updated. But the contents of the <p> are put in an effect anyway:

export default function App($$anchor) {
  let a = 1;
  let b = 2;
  var p = root();
+  var text = $.child(p);

-  p.textContent = `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`;
+  $.reset(p);
+  $.template_effect(() => $.set_text(text, `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`));
  $.append($$anchor, p);
}

Whatever logic is used for determining whether it's a = 1 or a = $.state(1) should also be used for determining whether to create an effect.

Reproduction

link

Logs

No response

System Info

next

Severity

annoyance

@Ocean-OS
Copy link
Contributor

I haven't had a chance to look deeply into the compiler code, but I think we'd start here and take the algorithm that determines the staticness of a $state and apply it to the functions here, here, and here.

@Ocean-OS
Copy link
Contributor

Ocean-OS commented Nov 12, 2024

Similarly, I think it'd be useful if we determined when any state updates happen to see if we really need to make a value a $.state. For example, in this code, a doesn't necessarily need to become a $.state.
If we could, (I'm not sure how doable this is), we could just figure out the updated value of a state and assign it at the declaration. Example:

let a = $state(1);
a++;
//becomes
let a = 2; //assuming `a` doesn't update anywhere else

@Ocean-OS
Copy link
Contributor

export default function App($$anchor) {
  let a = 1;
  let b = 2;
  var p = root();
+  var text = $.child(p);

-  p.textContent = `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`;
+  $.reset(p);
+  $.template_effect(() => $.set_text(text, `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`));
  $.append($$anchor, p);
}

Out of curiosity, is there a reason you chose to use p.textContent instead of $.set_text?

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

Successfully merging a pull request may close this issue.

2 participants