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());
});

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()));
});

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));
});

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: