Why re-select createSelector in this @ngrx example?

What does the following code snippet do? This is taken from this file .

export const getCollectionLoading = createSelector(getCollectionState, fromCollection.getLoading);

fromCollection.getLoading is only true or false , so is it possible to achieve any optimization using createSelector ?

in

 export const getCollectionLoaded = createSelector(getCollectionState, fromCollection.getLoaded); export const getCollectionLoading = createSelector(getCollectionState, fromCollection.getLoading); export const getCollectionBookIds = createSelector(getCollectionState, fromCollection.getIds); 
+5
source share
2 answers

According to the example application comments:

 /** * Every reducer module exports selector functions, however child reducers * have no knowledge of the overall state tree. To make them useable, we * need to make new selectors that wrap them. **/ 

For example, in the /collection.ts reducers of the selector at the bottom of the file, they only refer to a collection slice:

 export const getLoaded = (state: State) => state.loaded; export const getLoading = (state: State) => state.loading; export const getIds = (state: State) => state.ids; 

These collection selectors cannot be used with state.select () because state.select expects to work with the entire AppState. Therefore, in /index.ts reducers, the selector is then wrapped with another selector so that it works with the entire AppState:

 export const getCollectionLoading = createSelector(getCollectionState, fromCollection.getLoading); 

Let's get back to your question: why should this be used for re-selection. Repeated selection in this case does not provide any optimizations. Thus, the main purpose of reselection is that it provides the ability to arrange selectors.

Using this composition function, we can make collection.ts only selectors for cutting collections. Then in index.ts we can have a selector at the AppState level. In addition, we can have selectors that work on different sections of the store, such as this one:

 /** * Some selector functions create joins across parts of state. This selector * composes the search result IDs to return an array of books in the store. */ export const getSearchResults = createSelector(getBookEntities, getSearchBookIds, (books, searchIds) => { return searchIds.map(id => books[id]); }); 
+11
source

Yes, there may be a performance improvement. If computing fromCollection.getLoading is expensive, reselecting will avoid unnecessary recounts until getCollectionState returns the same value.

+1
source

Source: https://habr.com/ru/post/1269183/


All Articles