Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question: does reselect help with performance on higher-order functions? #575

Open
lindapaiste opened this issue May 13, 2022 · 2 comments

Comments

@lindapaiste
Copy link

I am writing a higher-order function as a helper for writing selectors on a Redux Toolkit slice and I'm wondering if it makes sense to use reselect here or not.

Here is how that might look with and without using createSelector:

const subSelectV1 = <T>(subSelector: (subState: MySliceState) => T) =>
    (state: RootState): T => subSelector(rootState.mySlice);

const subSelectV2 = <T>(subSelector: (subState: MySliceState) => T) =>
    createSelector(
        (state: RootState): MySliceState => state.mySlice,
        subSelector
    );

Pros: In V2 the subSelector function would not get re-evaluated at all if there are changes to other slices but not to state.mySlice.

Cons: There is maybe some overhead associated with the memoization and caching?

subSelector here would be a simple selector that just accesses data from the state and does not transform it. I would then use the resulting selector as an input selector to createSelector in other places.


The goal is simply to save me from having to write state: RootState and state.mySlice everywhere when I am defining a whole bunch of selectors.

I can write:

export const selectSpecificThing = subSelect(state => state.someProperty);

Instead of:

export const selectSpecificThing = (state: RootState) => state.mySlice.someProperty;
@markerikson
Copy link
Contributor

I don't think there's going to be any harm in using Reselect here, if that's what you're asking. But also not sure if there's going to be much benefit either.

@lukeapage
Copy link
Contributor

It’s going to be very slightly slower to use reselect unless you have non trivial selectors eg if the selector

  1. Creates a new instance and non value type each time - then it will only be recreated if myslice changes so a simple reference check on the created item may lead to performance improvement (if you use react redux for instance)
  2. The selector returns a value type and the function is more complex than a loop to 1 and some equality comparisons and a extra function call

In those cases reselect may offer an advantage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants