0 day streak
javascript / expert
Snippet

Synchronized State Resets with linkedSignal()

The linkedSignal() function creates a writable signal that is linked to a source signal. When the source signal changes, the linked signal's value is automatically recalculated or reset based on the computation function, ensuring state consistency across dependent data.

snippet.js
javascript
1
2
3
4
5
6
7
8
const userId = signal(123);
const commentDraft = linkedSignal({
source: userId,
computation: (id) => `Draft for user ${id}: `,
});
// Updating userId automatically resets commentDraft
userId.set(456);
angular
Breakdown
1
const userId = signal(123);
Defines the source signal that triggers the update.
2
const commentDraft = linkedSignal({
Initializes a writable signal that tracks the source.
3
computation: (id) => `Draft for user ${id}: `
Determines the new value of the signal whenever the source changes.