Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Redux selectors that are both reusable and modular?

I am new to Redux and trying to figure out how to take full advantage of it.

When writing a selector for a module of the application, what part of the state tree should be passed to the selector so that the selector is both reusable and modular?

For example, given the code below, what is a good way to write selectModuleItemsById with a state shape similar to stateShapeExample?

let stateShapeExample = {
    module: {
        items: {
            firstItemId: {...},
            secondItemId: {...},
            ...
        }
    }
}

const selectModuleRoot = (state) => state.module;

// First Option: starts from the module root
const selectModuleItemById = (state, id) => state.items[id];

// Second Option: starts from the global root
const selectModuleItemById = (state, id) => state.module.items[id];

// Something Else: ???
const selectItemById = (state, id) => state[id];
like image 695
lowtex Avatar asked Sep 06 '25 06:09

lowtex


1 Answers

The short answer is that it's pretty tricky.

The best writeup on this that I've seen is Randy Coulman's series of posts on modularizing selectors:

  • Encapsulating the Redux State Tree
  • Redux Reducer/Selector Asymmetry
  • Modular Reducers and Selectors
  • Solving Circular Dependencies in Modular Redux

The general summary of that seems to be letting "module reducers" write selectors that know how to pick pieces of data out of their own state, then "globalizing" them at the app level based on where that module/slice is mounted in the state tree. However, since the module probably needs to use the selectors itself, you may have to move the registration / setup process into a separate file to avoid a circular dependency issue.

like image 87
markerikson Avatar answered Sep 09 '25 01:09

markerikson