Sub topic 3
Running Setup and Cleanup with `withHooks`
Assume you know Angular dependency injection, signals, and basic RxJS. A SignalStore hook runs code when the store is created or destroyed.
Setup and cleanup with `withHooks`
Use onInit for initial loading or setup. Use onDestroy to stop resources such as subscriptions, timers, or event listeners.
import { signalStore, withHooks, withMethods, withState } from '@ngrx/signals';
export const ClockStore = signalStore(
withState({ started: false }),
withMethods(() => ({
start(): void {
// Start a resource here.
},
})),
withHooks({
onInit(store) {
store.start();
},
onDestroy() {
// Release resources created by the store.
},
}),
);onInit runs once for each store instance. The lifetime depends on where the store is provided.
Managing collections with `withEntities`
withEntities adds signals for an entity array, an ID list, and an ID-to-entity map. Entity updaters keep collection changes consistent.
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import { addEntity, removeEntity, updateEntity, withEntities } from '@ngrx/signals/entities';
type Product = { id: number; name: string };
export const ProductsStore = signalStore(
withEntities<Product>(),
withMethods((store) => ({
add(product: Product) {
patchState(store, addEntity(product));
},
rename(id: number, name: string) {
patchState(store, updateEntity({ id, changes: { name } }));
},
remove(id: number) {
patchState(store, removeEntity(id));
},
})),
);Choosing a provider scope
Use { providedIn: 'root' } for shared application state. Provide the store in a component when each component instance needs isolated state. Component scope also makes cleanup predictable because destruction ends the store lifetime.
Sharing logic with `signalStoreFeature`
A custom feature packages state, computed signals, and behavior for reuse.
import { signalStoreFeature, withState } from '@ngrx/signals';
export function withRequestStatus() {
return signalStoreFeature(
withState({ requestStatus: 'idle' as 'idle' | 'pending' | 'done' }),
);
}Add withRequestStatus() to any compatible store.
Testing with `TestBed`
Inject the store, call its public methods, and read its signals.
const store = TestBed.inject(ProductsStore);
store.add({ id: 1, name: 'Pen' });
expect(store.entities()).toHaveLength(1);Exercise
When should a store use component-level providers?
Show answer
When each component instance needs independent state and a lifetime tied to that component.