Sub topic 9
Running setup and cleanup with withHooks
This chapter assumes you can create a store with signalStore, withState, withComputed and withMethods. It also assumes you know patchState and have met rxMethod. Here you will learn how a store runs code when it is created and when it is destroyed.
Why a store needs lifecycle hooks
A store often has work to do that no component asks for. It may load its first page of data, restore saved state, or start a polling timer. It also has to stop that work when it goes away.
You could ask each component to call store.load() in ngOnInit. That spreads the store's startup rules across every component that uses it, and a component can forget the call. withHooks moves that logic into the store. The store starts itself, and it cleans up after itself.
withHooks adds two hooks:
onInitruns once, when Angular creates the store instance.onDestroyruns once, when the injector that owns the store is destroyed.
The object form
The simplest form passes an object. Each hook receives the store as its argument.
import { patchState, signalStore, withHooks, withMethods, withState } from '@ngrx/signals';
type CounterState = { count: number };
export const CounterStore = signalStore(
{ providedIn: 'root' },
withState<CounterState>({ count: 0 }),
withMethods((store) => ({
increment(): void {
patchState(store, (state) => ({ count: state.count + 1 }));
},
})),
withHooks({
onInit(store) {
console.log('CounterStore created with count', store.count());
store.increment();
},
onDestroy(store) {
console.log('CounterStore destroyed at count', store.count());
},
}),
);The store argument contains everything declared above withHooks: state signals, computed signals and methods. It also works as the first argument of patchState. A hook can only see what was declared earlier in the signalStore call. If you place withHooks before withMethods, store.increment will not exist, and TypeScript reports an error.
The factory form
The object form has no place to keep a value that both hooks need. For that, pass a function that returns the hooks. The function runs once per store instance, and the hooks it returns can close over local variables.
import { patchState, signalStore, withHooks, withState } from '@ngrx/signals';
type ClockState = { now: number };
export const ClockStore = signalStore(
withState<ClockState>({ now: Date.now() }),
withHooks((store) => {
let timerId: ReturnType<typeof setInterval> | undefined;
return {
onInit() {
timerId = setInterval(() => patchState(store, { now: Date.now() }), 1000);
},
onDestroy() {
clearInterval(timerId);
},
};
}),
);timerId is created in the factory, assigned in onInit and read in onDestroy. Without the factory form you would need a module-level variable, and every instance of the store would share it.
ClockStore has no providedIn: 'root', so it is not provided anywhere yet. You provide it in a component's providers array. When that component is destroyed, Angular destroys the store and onDestroy clears the timer. A store without onDestroy here would keep calling patchState on a store nobody can read.
The injection context
Hooks run inside an injection context. This means you can call inject() and effect() directly in a hook, or in the factory function, without any extra setup.
import { effect, inject } from '@angular/core';
import { getState, patchState, signalStore, withHooks, withState } from '@ngrx/signals';
import { DOCUMENT } from '@angular/common';
type PrefsState = { theme: 'light' | 'dark'; pageSize: number };
const STORAGE_KEY = 'prefs';
export const PrefsStore = signalStore(
{ providedIn: 'root' },
withState<PrefsState>({ theme: 'light', pageSize: 20 }),
withHooks((store) => {
const storage = inject(DOCUMENT).defaultView?.localStorage;
return {
onInit() {
const saved = storage?.getItem(STORAGE_KEY);
if (saved) {
patchState(store, JSON.parse(saved) as Partial<PrefsState>);
}
effect(() => {
storage?.setItem(STORAGE_KEY, JSON.stringify(getState(store)));
});
},
};
}),
);The factory injects DOCUMENT, which is safer than touching window directly when the app renders on a server. onInit first restores saved preferences, then registers an effect. getState(store) reads every state signal, so the effect reruns after each patchState call and writes the new state back.
The effect belongs to the store's injector. Angular destroys it together with the store, so you do not need to destroy it in onDestroy.
Only call inject() and effect() synchronously. After an await, or inside a setTimeout callback, the injection context is gone and Angular throws an error.
Starting reactive work with rxMethod
The most common use of onInit is to start an rxMethod. You can pass a signal to an rxMethod, and it reruns whenever the signal changes.
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';
import { tapResponse } from '@ngrx/operators';
import { patchState, signalStore, withHooks, withMethods, withState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap } from 'rxjs';
type User = { id: number; name: string };
type UsersState = { users: User[]; query: string; loading: boolean; error: string | null };
export const UsersStore = signalStore(
withState<UsersState>({ users: [], query: '', loading: false, error: null }),
withMethods((store, http = inject(HttpClient)) => ({
setQuery(query: string): void {
patchState(store, { query });
},
loadByQuery: rxMethod<string>(
pipe(
tap(() => patchState(store, { loading: true, error: null })),
switchMap((query) =>
http.get<User[]>('/api/users', { params: { q: query } }).pipe(
tapResponse({
next: (users) => patchState(store, { users, loading: false }),
error: (err: Error) => patchState(store, { loading: false, error: err.message }),
}),
),
),
),
),
})),
withHooks({
onInit(store) {
store.loadByQuery(store.query);
},
}),
);onInit passes the store.query signal itself, not its current value. The rxMethod then loads data once at startup and again whenever setQuery changes the query. switchMap cancels a request that is still running when a new query arrives.
You do not need an onDestroy for this. An rxMethod called in an injection context ties its subscription to that context. When the store is destroyed, the subscription ends.
If you pass a plain value such as store.loadByQuery('abc'), the method runs once for that value. Pass a signal or an observable when you want it to keep reacting.
When hooks run
The timing depends on how the store is provided.
| Provider | Store created | `onInit` runs | `onDestroy` runs |
|---|---|---|---|
| `providedIn: 'root'` | First time something injects it | At that first injection | When the application is destroyed |
| In a component's `providers` | When that component is created | During component creation | When that component is destroyed |
| In a route's `providers` | When the route's injector first needs it | At that first injection | When the route's environment injector is destroyed |
The first row surprises people. A root store is lazy. If nothing injects it, onInit never runs, even though the store is "provided in root". A store that must start at application launch has to be injected somewhere early, for example in an app initializer or in the root component.
The last two rows decide how often a hook runs. A store in a component's providers array is created again for every instance of that component. Each instance gets its own timer, its own request and its own cleanup.
Several withHooks calls
A store can contain more than one withHooks. The hooks do not replace each other. Angular runs them in the order they appear in the signalStore call, and each one sees the members declared before it. This is how a custom feature, built with signalStoreFeature, can bring its own hooks and combine with the hooks of the store that uses it.
import { signalStore, withHooks, withState } from '@ngrx/signals';
export const LoggedStore = signalStore(
withState({ ready: false }),
withHooks({
onInit() {
console.log('first');
},
}),
withHooks({
onInit() {
console.log('second');
},
}),
);When this store is created, the console shows first and then second.
Common mistakes
- Putting
withHooksabove the members it uses. The hook only sees members declared earlier in the chain. - Passing
store.query()instead ofstore.queryto anrxMethod. The first form sends one value and never reacts to changes. - Expecting
onIniton a root store to fire at startup. It fires at first injection. - Calling
inject()after anawaitin a hook. Do all injection in the factory function or at the top of the hook. - Creating something manually, such as a timer, a listener or a subscription, and not releasing it in
onDestroy. Effects andrxMethodsubscriptions clean up on their own, but anything you start yourself does not.
Testing hooks
TestBed.inject creates the store, so onInit has already run when you get the instance back. To test onDestroy, destroy the injector with TestBed.resetTestingModule(), or provide the store in a small host component and destroy its fixture.
For an onInit that starts an rxMethod with an HTTP call, use provideHttpClient() and provideHttpClientTesting(). Then flush the request through HttpTestingController and assert on the state signals.
Summary
withHooksgives a store two lifecycle callbacks,onInitandonDestroy.- The object form is enough for simple setup. The factory form lets both hooks share local variables and call
inject(). - Hooks run in an injection context.
effect()andrxMethodsubscriptions end when the store is destroyed. - When hooks run depends on where the store is provided. A root store starts at first injection. A component-provided store lives and dies with its component.
Exercise
A SearchStore is provided in a component's providers array. Its onInit calls setInterval to refresh results every 30 seconds and does not store the timer id. The user opens and closes the component five times. What goes wrong, and how do you fix it?
Show answer
Each time the component is created, a new store is created and starts its own interval. Because no onDestroy clears the timer, all five intervals keep running after their components are gone, and they keep calling patchState on stores nobody uses. Fix it with the factory form of withHooks. Declare let timerId in the factory, assign it in onInit, and call clearInterval(timerId) in onDestroy.
Exercise
Your root-provided SettingsStore loads settings in onInit. A page that never injects the store shows no settings, and the HTTP request never appears in the network tab. Why, and what are two ways to fix it?
Show answer
A root store is created lazily, so onInit runs only when something first injects it. Nothing on that page injects it. One fix is to inject the store in the root component or another early place. The other is to inject it in an app initializer, so it is created at startup.