This is an Angular Tip but works with other frameworks/libs that use signals
🎓 INTRO
Every time a signal changes, all dependent computations are re-triggered.
This can be a performance bottleneck.
Consider a counter signal and a computed signal that returns a boolean to indicate if the counter isZero or not.
isZero = computed(() => this.counter() === 0);
This computed signal is used to change a color based on its value.
The color turns red when the counter is zero, and green otherwise.
Usage:
<span [style.color]="isZero() ? 'red' : 'green'">
The isZero()
function is called every time counter changes.
❌ ALTERNATIVE VERSION
You may also simplify the template creating a new computed Signal to set the color:
isZeroColor = computed(
() => this.counter() === 0 ? 'red' : 'green'
);
Usage:
<span [style.color]="isZeroColor()">
This setup works, but there's a catch!
The isZeroColor()
function is called every time counter changes, even when not necessary.
I.e. from 2 to 3, from 3 to 4, since the value is always false.
🚀 What if we could minimize the computations?
💡 How? Creating a computed signal from another computed signal.
isZeroColor = computed(() => this.isZero() ? 'red' : 'green');
🔑 Key Benefit: isZeroColor
is recalculated only when isZero changes.
This means if counter changes from 1 to 2, isZeroColor doesn’t recompute since isZero remains false. It only recomputes when counter goes from 1 to 0, changing isZero from false to true.
🌟 Result: We've just optimized our application! This approach reduces unnecessary computations, leading to better performance.
🤔 Why This Matters: In complex applications, such optimizations can significantly reduce the workload on the browser, leading to smoother and faster UIs.
Top comments (3)
Hi Fabio Biondi,
Your article is very cool
Your tip is very useful
Thanks for sharing
Thank you João 🙏
Interesting.
Very useful for apps that use a lot of computed signals in the components