Skip to content

Weird interaction between patchState in effect and watchState #5165

@rmeyergh

Description

@rmeyergh

Which @ngrx/* package(s) are the source of the bug?

signals

Minimal reproduction of the bug/regression with instructions

When the "trigger" button in the component below is clicked, the watcher will trigger as seen in the console output. It will not happen as soon as patchState inside the effect or triggerService.trigger() inside the watcher are wrapped with untracked() but I don't think that should be necessary. If it is it should at least be mentioned in the documentation. I have no explanation why that happens.

import { Component, effect, inject, Injectable, signal } from '@angular/core';
import { patchState, signalStore, watchState, withHooks, withState } from '@ngrx/signals';

@Injectable({ providedIn: 'root' })
export class TriggerService {
  trigger = signal(0);
}

const MyStore = signalStore(
  withState({}),
  withHooks({
    onInit(store, triggerService = inject(TriggerService)) {
      effect(() => {
        patchState(store, (state) => ({
          ...state,
        }));
      });

      watchState(store, () => {
        if (triggerService.trigger()) console.log('watcher triggered');
      });
    },
  }),
);

@Component({
  selector: 'app-root',
  providers: [MyStore],
  template: `<button (click)="trigger()">trigger</button>`,
})
export class App {
  private readonly triggerService = inject(TriggerService);
  private readonly store = inject(MyStore);

  trigger() {
    this.triggerService.trigger.update((count) => count + 1);
  }
}

Expected behavior

The watcher should not react to the signal when the button is clicked.

Versions of NgRx, Angular, Node, affected browser(s) and operating system(s)

NgRx: 21.1.0
Angular: 21.2.14
Node: 24.13.0
Browser: Chrome 148.0.7778.216
OS: macOs Tahoe 26.5.1

Other information

No response

I would be willing to submit a PR to fix this issue

  • Yes
  • No

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions