الانتقال إلى المحتوى
FrontendAngular· 8 دقائق للقراءة

Stop Syncing Signals with effect(): Use computed() and linkedSignal()

An effect runs later, so the copy it keeps is stale in between. Derive state; keep effects at the edges.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A product search component keeps its 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

The belief: an runs whenever the signals it reads change, so "when query changes, update matches" is exactly what it's for. It's the standard way to keep one signal in sync with another.

It looks like the right tool because it reads like a watcher, and watchers are how many of us learned reactivity: a 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

A 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.

An effect works the other way. Writing to a signal it reads only marks it dirty, and Angular runs it later: a component's effects run during change detection, just before that component is checked. Until then, 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.

TypeScript product-search.ts
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())));    });  }}

The fixed version has less code and one fewer piece of state. 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()

The harder case is state that is derived and editable at once. The search page highlights a selected product: by default the first match, but the user can click another one, and the pick should survive a new query as long as the product is still in the list. 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:

TypeScript product-picker.ts
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],  });}

A click calls 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

The guide's rule of thumb: if you're copying data from one signal to another with an effect, move your source of truth higher up and use 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.

What you're writingUseWhy
A value calculated from other signalscomputed()Lazy and memoized, never stale when read
State the user can set that must follow a sourcelinkedSignal()Writable, recomputed when the source changes
Data that loads when a signal changesresource()Tracks its params and aborts outdated loads
Pushing state to storage, logs or a libraryeffect()Leaving the signal graph is its job
Reading or writing the DOM after renderafterRenderEffect()Runs after Angular commits DOM changes

How to apply it in your project

  1. List the effects that write signalsSearch your code for effect( and look for .set( or .update( inside the callback. Each one is a candidate.
  2. 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().
  3. Use linkedSignal() for editable derived stateSelections, drafts and defaults that the user can override but that must follow a source become linkedSignal(), using previous to keep what's still valid.
  4. Keep effects at the edgesWhat 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(), with previous to keep valid user choices.
  • Effects are for leaving the signal graph: storage, logging, the DOM and libraries that don't speak signals.

📚 المصادر

  1. Effects — Angular
  2. Angular Signals — Angular
  3. Dependent state with linkedSignal — Angular
  4. Async reactivity with resources — Angular
  5. CreateEffectOptions — Angular API

التعليقات (0)