Hey, I've been messing around with nested computeds as an optimization strategy & have noticed some stuff I find weird. I'm wondering if anyone understands & could help me out by explaining what's going on 🙂
I'd expect the first computed "unstable" to behave the same as "stable"...where a value update only triggers the internal computed a-la SolidJS. But in the "unstable" case it also triggers the outer one on every value change.
So my question is why wrapping the inner computed in an object makes a difference? o.O
P.S. I've also asked this question on the Angular subreddit, I'll update both if we figure something out 🙂
function nestedTest(source: WritableSignal<number[]>) {
const length = computed(() => source().length);
const unstable = computed(() =>
Array.from({ length: length() }).map((_, i) => computed(() => source()[i])),
);
effect(() => {
console.log('unstable', unstable()); // triggers once (first time) & every time source changes, underlying signals also trigger
});
const stable = computed(() =>
Array.from({ length: length() }).map((_, i) => ({
value: computed(() => source()[i]),
})),
);
effect(() => {
console.log('stable', stable()); // triggers once (first time), but does not when source changes. underlying signals also trigger
});
return {
trigger: () => {
source.update((cur) => cur.map((v, i) => (i === 1 ? v + 1 : v))); // update the second element
},
};
}