DEV Community

Cover image for TIP: how to boost your app's performance with (Angular) computed signals
Fabio Biondi
Fabio Biondi

Posted on

TIP: how to boost your app's performance with (Angular) computed signals

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);
Enter fullscreen mode Exit fullscreen mode

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'">
Enter fullscreen mode Exit fullscreen mode

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'
);
Enter fullscreen mode Exit fullscreen mode

Usage:

<span [style.color]="isZeroColor()">
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

🔑 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)

Collapse
 
jangelodev profile image
João Angelo •

Hi Fabio Biondi,
Your article is very cool
Your tip is very useful
Thanks for sharing

Collapse
 
fabiobiondi profile image
Fabio Biondi •

Thank you João 🙏

Collapse
 
railsstudent profile image
Connie Leung •

Interesting.

Very useful for apps that use a lot of computed signals in the components