Angular Signals - Timing
Tags: angular, webdev, frontend, signals
Published: 2023-05-06 21:23:08

Angular v16 has been released, and my article is about the most important feature that this release brings: Angular Signals. I'll show you, how and when `computed()` and `effect()` run the functions you send to them.

While there are no official tutorials about Signals yet, the API is described in the RFC and the source code is available.

Some developers think that Angular Signals are quite similar to signal implementations in other frameworks and libraries, but there are some important differences to note.

Describing `computed()`, RFC says:

> Computations are lazy: the computation function is not invoked, unless someone is interested in (reads) its value.

Also:

> Computed values are not updated if there was no update to the dependent signals

These are quite important differences.

About the effects, RFC says:

> effects will execute at least once;
>
> effects will execute in response to their dependencies changes at some point in the future;
>
> effects will execute minimal number of times: if an effect depends on multiple signals and several of them change at once, only one effect execution will be scheduled.

To see it in practice, let's write a test. I wrote it as a part of a regular [Angular app, using StackBlitz](https://stackblitz.com/edit/angular-signals-timing?devToolsHeight=33&file=src/main.ts), to let you launch it in the browser:

{% embed https://stackblitz.com/edit/angular-signals-timing?embed=1&file=src/main.ts %}

The next part of this article is located right there in the code. I recommend [opening it](https://stackblitz.com/edit/angular-signals-timing?devToolsHeight=33&file=src/main.ts) and reading the comments in the code (and looking at the console).

For the sake of completeness, I'll quote the code here.

_If you are reading it on a small screen, I recommend turning it into landscape mode._

> `expect()` is a small helper, similar to what you use in real tests: `expect(variable, toHaveThisValue)`.

## computed()

```ts
testComputed() {
// Our signals
const x = signal(1);
const y = signal(-1);

// Counter of how many times our computed signal was run:
let runs = 0;

const c = computed(() => {
  runs++;
  return Math.pow(x(), y());
});

// The signal has been created, and no runs are expected at this time.
expect(runs, 0);

c();
// Now, we do expect one run since the computed signal was just read (unwrapped).
expect(runs, 1);

// Let's update our signals and check if it will cause a recomputation of the computed signal.
x.set(2);
y.set(2);

// Because computed Angular Signals are lazy, there will be no runs until the computed signal is read.
expect(runs, 1);

setTimeout(() => {
  // Even in the next microtask.
  expect(runs, 1);

  // But when we read it...
  const v1 = c();

  // ...it will be recomputed once:
  expect(runs, 2);
  // and we will get the computation for the latest values of the involved signals.
  expect(v1, 4);

  // Multiple modifications of the signals...
  x.set(3);
  x.set(4);
  x.set(5);
  x.set(6);

  // ...will not affect the number of runs.
  expect(runs, 2);

  // The computed signal will run as many times as it was read...
  const v2 = c();
  expect(runs, 3);
  expect(v2, 36);

  // ...but only if the involved signals were modified between the reads!
  const v3 = c();
  expect(runs, 3);
  expect(v3, 36);
  // This is because computed() uses memoization.
  // Let's modify one of the signals to check it:
  x.set(2); // y() is currently = 2
  const v4 = c();
  expect(runs, 4);
  expect(v4, 4);
});
}
```
## effect()

```ts
testEffect() {

const x = signal(1);
const y = signal(-1);

let runs = 0;
// The value we are modifying as a side-effect.
let v = 0;

effect(() => {
    runs++;
    v = Math.pow(x(), y());
});

// As soon as it is created, effect() will run...
expect(runs, 0);
// ...but at some point in the future ;)
expect(v, 0);

// Let's fast forward to the future.
setTimeout(() => {
  // We haven't modified our signals, so this run is just
  // a scheduled run from the creation moment.
  expect(runs, 1);
  expect(v, 1);

  // Now let's modify our signals.
  x.set(2);
  // Both of them: 2 modifications we made in total.
  y.set(3);

  // Despite these modifications, runs still equals 1,
  expect(runs, 1);
  // and the value is not updated.
  expect(v, 1);

  x.set(9);
  y.set(2);

  // Even if we make multiple synchronous modifications
  expect(runs, 1);
  expect(v, 1);

  // This is because the next run is scheduled for some point in the future.
  setTimeout(() => {
    // And in that future, we can see that our effect() was run once
    expect(runs, 2);
    // with the latest values of the signals:
    expect(v, 81);

    // Will effect() run if a signal is updated but not changed?
    x.set(9);
    setTimeout(() => {
      // No, memoization works here as well:
      expect(runs, 2);
      expect(v, 81);
    });
  });
});
}
```

I hope that the format of this article wasn't too uncomfortable for you :) Sometimes things are easier to present as comments in the code.

---
💙 _If you enjoy my articles, consider [following me on Twitter](https://twitter.com/eugeniyoz), and/or [subscribing](https://medium.com/@eugeniyoz) to receive my new articles by email._  
🎩️ _If you or your company is looking for an Angular consultant, you can [purchase my consultations on Upwork](https://www.upwork.com/services/consultation/development-it-evgeniy-1696285343741362176?ref=project_share)._