Sub topic 9
Running setup and cleanup with withHooks
This chapter assumes you have read the earlier chapters on withState, patchState and withMethods. You should also know Angular's effect and the idea of an injection context.
Why a store needs lifecycle hooks
Some work belongs to the store itself, not to a component. Examples are restoring saved settings, starting a first request, or stopping a timer. If a component triggers that work from ngOnInit, every component that uses the store has to remember to do it.
withHooks lets the store run this logic itself. It supports two hooks:
onInitruns once, when Angular creates the store.onDestroyruns when the store's injector is destroyed.
When that happens depends on where you provide the store. A root store is destroyed when the application is destroyed. A store provided in a component's providers array is destroyed with that component. The scoping chapter covers this in more detail.
The object form: onInit with an effect
The simplest form passes an object with hook functions. Each hook receives the store. The next example restores settings from localStorage and then saves every later change.
import { effect } from '@angular/core';
import { getState, patchState, signalStore, withHooks, withState } from '@ngrx/signals';
type SettingsState = { theme: 'light' | 'dark'; pageSize: number };
const initialState: SettingsState = { theme: 'light', pageSize: 20 };
const STORAGE_KEY = 'app-settings';
export const SettingsStore = signalStore(
{ providedIn: 'root' },
withState(initialState),
withHooks({
onInit(store) {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
patchState(store, JSON.parse(saved) as Partial<SettingsState>);
}
effect(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(getState(store)));
});
},
}),
);getState reads the whole state as a plain object and tracks every state signal, so the effect reruns after any change. Hooks run inside an injection context. That is why calling effect directly in onInit works, and Angular destroys that effect with the store. You do not need to clean it up yourself.
The factory form: private variables and inject
Sometimes the setup and the cleanup need to share a value, such as a timer ID. You may also need inject to get a service. In that case, pass a function that returns the hooks. The function body runs once per store instance, so local variables stay private to that instance.
import { patchState, signalStore, withHooks, withState } from '@ngrx/signals';
export const ClockStore = signalStore(
withState({ seconds: 0 }),
withHooks(() => {
let timerId: ReturnType<typeof setInterval> | undefined;
return {
onInit(store) {
timerId = setInterval(() => {
patchState(store, (state) => ({ seconds: state.seconds + 1 }));
}, 1000);
},
onDestroy() {
clearInterval(timerId);
},
};
}),
);Without onDestroy, the interval would keep running after the store is gone. It would also keep the store in memory. The store above has no providedIn: 'root', so you provide it where it is needed, for example in a component's providers.
What belongs in a hook
| Task | Good fit for a hook? |
|---|---|
| Restore or persist state | Yes |
| Start a request that follows a signal, using `rxMethod` | Yes |
| Start and stop timers or listeners | Yes, pair `onInit` with `onDestroy` |
| Logic that only one component needs | No, keep it in that component |
| Long synchronous work | No, it delays creation of the store |
rxMethod subscriptions that you start with a signal are cleaned up automatically when the store is destroyed. You only need onDestroy for resources that Angular does not manage for you.
Common errors
- Reading the store too early. In
onInit, state and methods from features declared beforewithHooksexist. Features declared after it are not available. PutwithHookslast. - Calling
effectoutside the hooks' injection context. If you create an effect inside a callback, such as asetTimeout, Angular throws an error. Create it directly inonInit, or pass aninjector. - Forgetting that a root store is created lazily.
onInitdoes not run until something first injects the store. It does not run at application startup. - Leaking resources. Every
addEventListenerorsetIntervalinonInitneeds a matching removal inonDestroy.
Exercise
A store provided in a component's providers array starts a setInterval in onInit. Where should you stop it, and why does the timer need a shared variable between the two hooks?
Show answer
Stop it in onDestroy, which runs when the component and its store are destroyed. Both hooks must reach the same timer ID. Use the factory form of withHooks, declare let timerId in the factory function, assign it in onInit and pass it to clearInterval in onDestroy.