Skip to main content

Recipes

Selectors Optimization

tip

Beware of premature optimizations

Imagine we have a todos store and we subscribe to the following selectors twice, at two different places simultaneously:

todos.repository.ts
export const todos$ = store.pipe(selectAllEntities());

// One component
useObservable(todos$) // React
todos$ | async // Angular

// Second component
useObservable(todos$) // React
todos$ | async // Angular

Due to the nature of observables, the selectAllEntities() operator will map over the entities twice, once for each subscription. We can use the shareReplay operator to optimize it:

todos.repository.ts
import { shareReplay } from 'rxjs/operators';

export const todos$ = store.pipe(selectAllEntities(), shareReplay({ refCount: true }))

With this change, the selectAllEntities operator will now share the result with every subscriber.

Reset Stores

Resetting your stores can be useful when you want to clean the store's data upon user logout. We can combine the registry and store.reset() to create a resetStores function:

import { getRegistry } from '@ngneat/elf';

export function resetStores() {
getRegistry().forEach(store => store.reset())
}