preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.81k stars 95 forks source link

Question about effects observing computed signals #220

Closed yurivish closed 2 years ago

yurivish commented 2 years ago

Hi, I'm playing around with Preact Signals and have a question about an interesting behavior I noticed.

The behavior is a difference between signal and computed.

Effects that observe signals only fire when the signals they observe change in value, so the following code:

const a = signal(0);
effect(() => console.log("a updated:", a.value));
a.value = 1;
a.value = 1;

prints this, with one line per unique value of a:

a updated: 0
a updated: 1

However, it seems that effects that observe computed signals fire when the underlying signals change, even if the computed value stays the same, so the following code

const a = signal(0);
const b = computed(() => 0 * a.value); // always returns zero
effect(() => console.log("b updated:", b.value));
a.value = 1;
a.value = 1;

Prints this, with one line per unique value of a, even though the values of b are the same every time:

b updated: 0
b updated: 0

I was wondering – is this intentional? I could potentially imagine use cases for it, but reading the docs I did not see this difference discussed and wanted to check.

Thanks for your work on Signals, by the way – I came across them via Ryan Carniato and it seems like a great library!

marvinhagemeister commented 2 years ago

Thanks for checking out signals! No, this is not intentional and a regression when we rewrote the internals recently. The fix has been merged #205 and we'll cut a new release shortly.

yurivish commented 2 years ago

Thanks!