#Fine-grained reactivity for signals that hold an object

6 messages · Page 1 of 1 (latest)

wicked pine
#

Hello. I have a question regarding Signals.
Let's say that we have a signal that takes an object as a value.
state = signal({name: 'T', age: 30})

and an effect that logs something for when the name changed.
effect(() => console.log(name changed ${state().name}))

if I were to update the state age, by using update:
this.state.update((s) => ({ ...s, age: 40 }))

The effect would also trigger, logging the fact that the name changed.
In truth, the object changed, so that makes sense.
But my question is, is there a way to achieve fine-grained reactivity so that this scenario does not happen?
I am looking forward for an answer. Thank you very much!

winter linden
#

You can use a computed:

state = signal({name: 'T', age: 30});
name = computed(() => this.state().name);

effect(() => console.log('name changed', this.name());
wicked pine
#

tried with computed, but the effect still executes.
also, having a separate computed would defeat the initial purpose, of grouping multiple values in a single signal

winter linden
#

And I am not sure why that defeats the purpose.

wicked pine
#

well, I would group multiple props in a single Signal object, so I don't have multiple signals with primitives. by creating separate computeds, that's why I consider that it defeats (my) purpose.