I am working in Angular using the new signals API. I have an input signal that I am reading to create other computed signals, and am also directly reading inside of a template, like so:
Template:
<p>{{this.inputSignal()}}</p>
Typescript:
export class MyComponent {
inputSignal = input.required();
computedSignal1 = computed(() => {
this.inputSignal().toUpperCase();
})
computedSignal2 = computed(() => {
this.inputSignal().toLowerCase();
})
}
An engineer at my company recommended making a single computed signal for the input signal that I then read in all of these places because computed signals are explicitly cached and lazily evaluated. That code would look like this:
Template:
<p>{{this.inputSignalComputed()}}</p>
Typescript:
export class MyComponent {
inputSignal = input.required();
inputSignalComputed = computed(() => this.inputSignal());
computedSignal1 = computed(() => {
this.inputSignalComputed().toUpperCase();
})
computedSignal2 = computed(() => {
this.inputSignalComputed().toLowerCase();
})
}
In my mind, this is overengineering the problem, as even if the inputSignal is evaluated multiple times since it's not cached, it's not like it's constantly being updated.
Does this overcomplicate signals, or is there some benefit from doing it the computed/cached way that I'm missing?
Every signal has their value memoized. A computed that's only reading another signal value is basically useless.
Also,
You could use a transform
instead here and drop the computed !
inputSignal = input.required<string, string>({transform: (val) => val.toUpperCase()});