Managing associated state is now even easier

Boo! Scared? Don't be afraid. Angular 19 is just around the corner and introduces a powerful new primitive called linkedSignalwhich will help you manage complex state in your applications. This is an alternative to using effect to simply update a signal based on a change in another signal. Not everyone in the community agreed (as always), some promoted the idea of ​​using computed instead of effectto reset signals based on a change in another signal.

linkedSignal is a feature designed to simplify this process by allowing you to link signals so that their values ​​are automatically synchronized based on a dependency. This is useful for creating reactive data where one value needs to be automatically updated when another value changes.

Let's look at an example

Let's say we have a signal that represents the number of rubles in the user's account:

const amountRubles = signal(700);

Now let's create a signal that will automatically recalculate our value in yuan:

const amountYuan = linkedSignal(() => amountRubles() / 13.63);

amountRubles and amountYuan are returned WritableSignalis an advanced signal interface that allows you to set/update values ​​and make them read-only.

The same code, but written using effect:

const amountYuan = signal(amountRubles() / 13.63);
effect(() => {
  amountYuan.set(amountRubles() / 13.63);
});

The result when changing the main signal is the same, the associated one will automatically change:

console.log(amountRubles()); // 700
console.log(amountYuan()); // 51.35

amountRubles.set(1000);

console.log(amountRubles()); // 1000
console.log(amountYuan()); // 73.36

There are situations when you need the ability to set more flexible settings. linkedSignal allows you to pass an object in which the update logic will be written:

selectedCity = signal('Москва');
weatherSignal = linkedSignal({
    source: () => this.selectedCity(), // Базовый сигнал (источник)
    computation: (city, previous) => {
      if (previous?.source === city && previous?.value) {
        // Если город не изменился, используем предыдущее значение
        return previous.value;
      }
      // Получение прогноза из API при изменении города
      return this.fetchWeather(city);
    },
    equal: (newVal, oldVal) => newVal.temperature === oldVal.temperature
    // equal предотвращает лишние обновления, если температура осталась прежней
  });

This approach allows you to create linkedSignalwhich automatically updates only if the temperature for the selected city changes, minimizing unnecessary redraws.

Advantages

  • Automatic data synchronization
    When one state changes, all data associated with it is updated automatically. This allows you to avoid “manual” recalculations and synchronization, which reduces the likelihood of errors

  • Reactivity without additional dependencies
    linkedSignal makes the code more straightforward, as it allows you to work with reactive data without the traditional RxJS

  • Simplify logic and improve readability
    Usage linkedSignal reduces the amount of code to handle reactivity. When dependencies are declared declaratively in a function linkedSignalthe code becomes cleaner and easier to maintain, since you can see exactly which values ​​affect the associated signal

  • Increased productivity
    linkedSignal optimizes calculations by causing recalculation only in those places where the state has actually changed. This reduces the load on the application compared to inefficient recalculations

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *