
Stop Syncing Signals with effect(): Use computed() and linkedSignal()
- كاتب موثّق
- Angular 22
محتويات المقال
matches list in sync with an effect, and the page works. Then a unit test sets query to 'lap', reads matches(), expects one laptop and gets the full catalog. A teammate adds fixture.detectChanges() before the assertion, the test passes, and the team notes that "signals are async". They aren't: query.set() and every signal read after it are synchronous. The effect is the part that runs later.
The common misconception
query changes, update matches" is exactly what it's for. It's the standard way to keep one signal in sync with another.
subscribe() that pushes into a BehaviorSubject, a Vue watch, a React useEffect that calls setState. It also works most of the time, since the screen shows the right list after each keystroke. Early versions of effect() even refused signal writes unless you passed allowSignalWrites; that option is now deprecated because writes are allowed by default, which can read like a blessing. Angular's own guide says the opposite: effects should be the last API you reach for.
What actually happens
computed() is pulled; an effect is scheduled
computed() is lazy and memoized. Writing query.set('lap') doesn't run anything; it marks matches as stale. The next read of matches(), from a template, a click handler or a test, recomputes it on the spot and returns the new list. There's no moment when a reader can see the old value.
matches holds the previous list. Any code that writes query and reads matches in the same synchronous block, like a handler that opens the only result when Enter is pressed, or a unit test, sees stale data. When the effect finally runs, its write lands in the middle of change detection, so Angular has more to check. The docs list the costs of propagating state this way: NG0100 errors (ExpressionChangedAfterItHasBeenCheckedError), infinite circular updates, and unnecessary change detection cycles.
import { Component, effect, input, signal } from '@angular/core';@Component({ selector: 'app-product-search', template: ` <input #box (input)="query.set(box.value)" /> @for (p of matches(); track p.id) { <p>{{ p.name }}</p> } `,})export class ProductSearch { readonly products = input.required<Product[]>(); readonly query = signal(''); readonly matches = signal<Product[]>([]); constructor() { // A copy, refreshed later, during change detection effect(() => { this.matches.set(this.products().filter(byName(this.query()))); }); }}import { Component, computed, input, signal } from '@angular/core';@Component({ selector: 'app-product-search', template: ` <input #box (input)="query.set(box.value)" /> @for (p of matches(); track p.id) { <p>{{ p.name }}</p> } `,})export class ProductSearch { readonly products = input.required<Product[]>(); readonly query = signal(''); // Derived when read, so it's current right after query.set() readonly matches = computed(() => this.products().filter(byName(this.query())), );}matches can't drift from products and query because it doesn't store a copy of anything, and it isn't writable, so no other code can overwrite it by mistake. The filter runs only when matches() is read after one of its two dependencies changed.
When the user can change it too: linkedSignal()
computed() can't take the click, because it isn't writable. The effect version reads selected() to check it and writes selected to reset it, so it depends on its own output. A is the API built for this:
import { Component, input, linkedSignal } from '@angular/core';@Component({ selector: 'app-product-picker', templateUrl: './product-picker.html', // buttons call selected.set(p)})export class ProductPicker { readonly matches = input.required<Product[]>(); // The user's pick while it's still listed, else the first match readonly selected = linkedSignal<Product[], Product | undefined>({ source: this.matches, computation: (list, previous) => list.find((p) => p.id === previous?.value?.id) ?? list[0], });}selected.set(p), like any writable signal. When matches changes, the computation runs with the new list and a previous object holding the old source and the old value, including a value the user set. It keeps the pick if it's still listed and falls back to the first match otherwise. Like computed(), it runs when read, so it's never a step behind. The explicit type arguments are required when you use previous.
What effects are actually for
computed() or linkedSignal(). Effects are for the edges, where signal state has to reach something that isn't a signal: saving query to localStorage, logging or analytics, drawing on a <canvas>, or feeding a chart library. For DOM work after Angular renders, afterRenderEffect() runs after the DOM is updated. Each of those is a by definition; filtering a list isn't.
computed() | ||
linkedSignal() | ||
resource() | ||
effect() | ||
afterRenderEffect() |
How to apply it in your project
List the effects that write signals Search your code for effect(and look for.set(or.update(inside the callback. Each one is a candidate.Replace pure copies with computed() If the written value depends only on signals the effect reads, delete the writable signal and the effect, and declare the value with computed().Use linkedSignal() for editable derived state Selections, drafts and defaults that the user can override but that must follow a source become linkedSignal(), usingpreviousto keep what's still valid.Keep effects at the edges What remains should push state out: to storage, logs, the DOM or a third-party library. In an async effect, read every signal before the first await; reads after it aren't tracked.
Key takeaways
An effect runs later, during change detection, so a signal it keeps in sync is stale in between. A value derived from other signals is a computed(): lazy, memoized and current whenever you read it.Writable state that must follow a source is a linkedSignal(), withpreviousto keep valid user choices.Effects are for leaving the signal graph: storage, logging, the DOM and libraries that don't speak signals.
التعليقات (0)