DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Improve Angular Signals performance with untracked function

Angular Signals are available for developers from Angular v16.

Signals provide a new way for developers to tell our templates (and other code) that our data has changed.

We can think of a signal as a value plus a change notification. A signal is just a particular type of variable that holds a value. However, unlike other variables, a signal is notified when the variable value changes.

This improves Angular's change detection, improving performance and making our code more reactive.

We can track signals using the computed() or effect() function.

However, sometimes we want to read a signal value without creating a dependency or triggering the reactive function when its value changes.

In such cases, we can use the untracked() function provided by Angular.

Give an example where we have two signals, a and b, and we want to log their values in an effect:

const a = signal('A!');
const b = signal('B!');

effect(() => {
  console.log(a(), b());
});
Enter fullscreen mode Exit fullscreen mode

This effect will run the function when either a or b signal emits a new value.

However, if we only want to log when a changes, not when b changes. We can achieve this by using the untracked() function with b signal like this:

const a = signal('A!');
const b = signal('B!');

effect(() => {
  console.log(a(), untracked(() => b()));
});
Enter fullscreen mode Exit fullscreen mode

The untracked() function will run the provided function and return its result without creating any dependencies.

The effect will only run when the a signal emits a new value. We can also simplify the code by passing the signal directly to the untracked() function:

const a = signal('A!');
const b = signal('B!');

effect(() => {
  console.log(a(), untracked(b));
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

The untracked() function is a handy tool in Angular for improving signal read performance and preventing unnecessary dependencies.


I hope you found it helpful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Nhan Nguyen,
Top, very nice and helpful !
Thanks for sharing.