Recently I released a new state management pattern. You should check it out.

In this article, we will learn about the select() operator and when it is better to use reselect when querying a normalized state.

Let’s start with a basic example, todos and visibility filter. Say we have a store that looks like this:

We want to show the user the list of todos according to the selected filter. To accomplish this, we need two things from our store, the selected filter, and all the todos.

Our store is observable, so we can subscribe to it to get the most recent value. Each time the value changes, we can get the new value and update the UI according to the new state.

Let’s start working without the select() operator so we can recognize the problem.

The problem in the above code is that each time the store value changes, we get a new value and the calcVisibleTodos() method runs.

If we change the current user, our store will change, and the calcVisibleTodos() will run even though the value of the todos or the visibility filter have not changed.

We only want to run the calcVisibleTodos() method if either the todos or the visibility filter changes. That’s where the select() operator comes to play.

The select() operator gives you an observable that calls distinctUntilChanged() internally, meaning it will only fire when the state actually changes. ( a reference check )

Let’s refactor our example to use the select() operator mixed with combineLatest .