Redux is an outstanding tool for managing state in JavaScript, particularly in conjunction with ReactJS. While it’s documented outstandingly, figuring out how to structure things in practice can be challenging.

Selectors

The section of the Redux docs covering React integration contains this

Example 1: Hierarchical Subjects

Imagine you’re writing a book tracking application, where books can be associated with zero or more subjects, and the subjects lie in a hierarchy: American History beneath History, and so on.

Normalizing our data

The analogy to a relational DBMS here

Performance?

Pushing the DBMS analogy further, we’ve basically created a view on our data. The downside is that every single time our store changes, the subject stacking will be re-worked, just as the underlying queries are re-executed whenever you query a view.

Performance, part 2

Now our subjects are completely re-stacked whenever any individual subject is changed. Returning to the indexed view analogy, this would be like an entire clustered index being re-built from scratch whenever any item in the underlying tables is changed — which of course modern engines don’t. It’s doubtful this will matter, but if this code were somehow performance intense / crucial, there’s nothing stopping you from manually memoizing the function, and only recomputing the portions of the tree that actually changed. Naturally this wouldn’t be easy, and should only be done if actually needed.

Example 2: Books’ Subjects

I won’t bother writing out all of the related code, as this post is already too long, but the same idea applies to having each book maintain a list of its subjects. While it’s tempting to stack each book’s subjects after the list is loaded, this has a couple of drawbacks: there’s now a temporal dependency, whereby the list of subjects must be present before the books are loaded; and the books’ subjects need to be re-stacked whenever a set of book results come back, and also whenever a subject is edited or deleted, so the affected books can have their list of subjects updated.