Sub topic 12
Sharing logic with signalStoreFeature
This chapter assumes you can already build a store with signalStore, withState, withComputed and withMethods. It also assumes you know how patchState updates state, how rxMethod and tapResponse handle requests, and the basics of TypeScript generics. Here you will package repeated store code into a reusable feature, constrain what a feature needs from its host store, and test the feature on its own.
Why extract a feature
Real applications repeat the same store code. Many stores track a request status, a page size, a selected item or a dirty flag. Copying that code into each store gives you several versions of the same logic that slowly drift apart.
signalStoreFeature solves this. It takes the same building blocks you already use (withState, withComputed, withMethods, withHooks and others) and returns a single feature. You can pass that feature to any signalStore call, or to another signalStoreFeature, in the same way as the built-in withEntities.
Correction: the diagram must be in the proper fence, so here it is.
A first feature
The feature below holds a request status and derives two signals from it. It lives in its own file, together with small updater functions that produce the state changes.
// request-status.feature.ts
import { computed } from '@angular/core';
import { signalStoreFeature, withComputed, withState } from '@ngrx/signals';
export type RequestStatus = 'idle' | 'pending' | 'fulfilled' | { error: string };
export function withRequestStatus() {
return signalStoreFeature(
withState<{ requestStatus: RequestStatus }>({ requestStatus: 'idle' }),
withComputed(({ requestStatus }) => ({
isPending: computed(() => requestStatus() === 'pending'),
error: computed(() => {
const status = requestStatus();
return typeof status === 'object' ? status.error : null;
}),
})),
);
}
export const setPending = (): { requestStatus: RequestStatus } => ({
requestStatus: 'pending',
});
export const setFulfilled = (): { requestStatus: RequestStatus } => ({
requestStatus: 'fulfilled',
});
export const setError = (message: string): { requestStatus: RequestStatus } => ({
requestStatus: { error: message },
});Two points about this file:
withRequestStatusis a function that returns a feature. Calling it each time you build a store creates a fresh feature, and it lets you add parameters later.- The updater functions are plain functions that return partial state.
patchStateaccepts them directly, so every store changes the status in the same way. They are not part of the feature, because a state change only needs a store to be passed topatchState.
Using the feature in a store
Add the feature to a store like any other with* function.
// orders.store.ts
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';
import { tapResponse } from '@ngrx/operators';
import { patchState, signalStore, withMethods, withState } from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap } from 'rxjs';
import {
setError,
setFulfilled,
setPending,
withRequestStatus,
} from './request-status.feature';
type Order = { id: number; total: number };
export const OrdersStore = signalStore(
{ providedIn: 'root' },
withState<{ orders: Order[] }>({ orders: [] }),
withRequestStatus(),
withMethods((store, http = inject(HttpClient)) => ({
load: rxMethod<void>(
pipe(
tap(() => patchState(store, setPending())),
switchMap(() =>
http.get<Order[]>('/api/orders').pipe(
tapResponse({
next: (orders) => patchState(store, { orders }, setFulfilled()),
error: (err: Error) => patchState(store, setError(err.message)),
}),
),
),
),
),
})),
);The store now exposes requestStatus, isPending and error next to orders. A component can write store.isPending() without knowing where it came from. A second store can add withRequestStatus() and get the same members with the same behavior.
Notice that patchState accepts several updaters in one call. { orders } and setFulfilled() are applied together, so there is a single state change instead of two.
Declaring what a feature needs
A feature often depends on members that the host store must supply. A feature that computes canRetry from requestStatus is useless in a store with no requestStatus. You can express this requirement as the first argument of signalStoreFeature, using the type helper.
// retry-hint.feature.ts
import { computed } from '@angular/core';
import { signalStoreFeature, type, withComputed } from '@ngrx/signals';
import type { RequestStatus } from './request-status.feature';
export function withRetryHint() {
return signalStoreFeature(
{ state: type<{ requestStatus: RequestStatus }>() },
withComputed(({ requestStatus }) => ({
canRetry: computed(() => typeof requestStatus() === 'object'),
})),
);
}The object passed first is an input constraint. It has no runtime effect, because type<T>() only carries a TypeScript type. At compile time, TypeScript checks that the store already contains a requestStatus state property of the right type before this feature is added. The constraint can also describe other member kinds, such as computed signals or methods. Check the API reference for your installed version for the exact keys, because the shape of this input has changed between releases.
Order matters. The feature that provides a member must come before the feature that requires it.
signalStore(
withRequestStatus(), // provides requestStatus
withRetryHint(), // requires requestStatus: compiles
);
signalStore(
withRetryHint(), // error: requestStatus is missing
withRequestStatus(),
);Features with configuration and generics
Because a feature is created by a function, the function can take arguments. Use them for initial values, names and options.
// page-size.feature.ts
import { patchState, signalStoreFeature, withMethods, withState } from '@ngrx/signals';
export function withPageSize(initialSize = 20) {
return signalStoreFeature(
withState({ pageSize: initialSize }),
withMethods((store) => ({
setPageSize(size: number): void {
patchState(store, { pageSize: size });
},
})),
);
}withPageSize(50) and withPageSize() produce the same members with different initial state.
The same function can also take type parameters, for example withSelection<T extends { id: number }>(). Use this when the feature works on a type that only the host store knows, such as an entity type.
Name collisions
A store has one flat set of members. If two features declare a member with the same name, the later one replaces the earlier one. Recent versions of the library log a warning in development mode when this happens, but you should not depend on that warning to find the problem.
Collisions are the main risk in a library of shared features. These habits reduce it:
- Give feature members specific names such as
requestStatusrather thanstatus. - Accept a name or prefix in the feature function when you expect two copies in one store.
withEntitiesdoes this with itscollectionoption, which produces members liketodoEntities. - Keep internal members private. In current versions, a state, computed or method name that starts with an underscore is not exposed on the finished store, but later features in the same definition can still use it. Confirm this for your version before relying on it.
Features, helpers or inheritance
Not everything shared needs a feature. Pick the smallest tool that works.
| What you share | Best tool | Reason |
|---|---|---|
| A state change such as `setPending()` | Plain updater function | It needs no store, only `patchState`. |
| A pure calculation | Plain function | A feature adds nothing here. |
| State plus computed signals plus methods | `signalStoreFeature` | The pieces always belong together. |
| Behavior that needs members from the host | `signalStoreFeature` with an input constraint | The compiler checks the host. |
| One-off logic in a single store | Inline in that store | Extraction costs more than it saves. |
A good rule is to extract after the second or third repetition, not before. A feature written for one store usually guesses wrong about what the other stores need.
Testing a feature in isolation
Test a feature without a real store by building a minimal store around it. The test then covers only the feature's behavior.
// request-status.feature.spec.ts
import { TestBed } from '@angular/core/testing';
import { patchState, signalStore } from '@ngrx/signals';
import {
setError,
setPending,
withRequestStatus,
} from './request-status.feature';
const TestStore = signalStore({ providedIn: 'root' }, withRequestStatus());
describe('withRequestStatus', () => {
it('derives isPending and error from requestStatus', () => {
const store = TestBed.inject(TestStore);
expect(store.isPending()).toBe(false);
patchState(store, setPending());
expect(store.isPending()).toBe(true);
patchState(store, setError('boom'));
expect(store.isPending()).toBe(false);
expect(store.error()).toBe('boom');
});
});Calling patchState directly in a test is fine here, because the store has no methods. A feature that needs an input constraint can be tested by placing a small withState before it in the test store.
Common errors
- Forgetting to call the factory.
signalStore(withRequestStatus)passes the function itself. WritewithRequestStatus(). - Wrong order. A feature with an input constraint placed before its provider fails to compile. Move the provider earlier.
- Mutating inside a feature. Features follow the same rule as stores: build new objects and pass them to
patchState. - Hiding too much. A feature that registers its own HTTP calls and hooks becomes hard to predict. Keep shared features small and focused on one concern.
- Shared state between stores. Each store gets its own copy of the feature's state, because the feature function runs per store. Two stores using
withRequestStatus()do not share a status.
Exercise
You write withRetryHint() with the input constraint { state: type<{ requestStatus: RequestStatus }>() }. A teammate adds it to a store that has withState({ orders: [] }) but not withRequestStatus(). What happens, and how do you fix it?
Show answer
The TypeScript compiler reports an error, because the store has no requestStatus state property. The constraint has no runtime effect, so the check happens only at compile time. Fix it by adding withRequestStatus() to the store before withRetryHint().
Exercise
Two stores both use withPageSize(10). A component calls setPageSize(50) on the first store. What is pageSize() on the second store, and why?
Show answer
It stays 10. The feature function runs once per store definition, and each store instance holds its own state, so the two stores do not share anything.