Maru
Maru

Reputation: 41

reselect CreateStructuredSelector difference in properties

Maybe this is not necessarily a reselect question

const makeSelectError = () => createSelector(
  selectGlobal,
  (globalState) => globalState.get('error')
);

and in reselect we use

const mapStateToProps = createStructuredSelector({
  error: makeSelectError(),
});

why can't we use like below?

const makeSelectError = createSelector(
      selectGlobal,
      (globalState) => globalState.get('error')
    );

and use like below in reselect

const mapStateToProps = createStructuredSelector({
  error: makeSelectError,
});

Are there any issues/disadvantages with my code, or is that a standard practice?

Upvotes: 2

Views: 5187

Answers (2)

Chad Edrupt
Chad Edrupt

Reputation: 1584

Not only is the second way valid and correct it has other advantages.

With the first snippet you provide:

const makeSelectError = () => createSelector(
  selectGlobal,
  (globalState) => globalState.get('error')
);

makeSelectError is a factory function in that every time it is called it is returning a new and unique selector.

This means that every time a simple mapStateToProps function is called a new selector will be made and the result of the selector will be computed again. This means that you will be losing the key benefit of reselect that is memoization.

So for simple cases you could just do the following:

const getSomePieceOfState = state => state.someArea.someDetail;
const getAnotherPieceOfState = state => state.anotherArea.anotherItem;

const getSomeCombinedState = createSelector(
  getSomePieceOfState,
  getAnotherPieceOfState,
  (somePiece, anotherPiece) => somePiece + anotherPiece
);

const mapStateToProps = state => ({
  someProp: getSomeCombinedState(state)
});

Note. it's common to prefix the name of selectors with get and to prefix the name of a selector factory (a function that returns a selector) with makeGet.

Some times creating a selector factory is necessary though if you wan't to make a selector that is dependant on a property that is not in the state.

You can read more about that here Accessing React Props in Selectors

Upvotes: 4

Patrik Prevuznak
Patrik Prevuznak

Reputation: 2261

You're doing it absolutely right in the second example. This is a standard practice.

There's no need to do wrap makeSelectError to another function.

Upvotes: 1

Related Questions