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

useSelector not memoized? #68

Open
froatsnook opened this issue Oct 10, 2020 · 0 comments
Open

useSelector not memoized? #68

froatsnook opened this issue Oct 10, 2020 · 0 comments

Comments

@froatsnook
Copy link

Hi, I believe that selectors aren't memoized (per app state), though I'm not sure if this is an intended feature. I believe I'm using reductive in the normal manner, as follows:

I have a file called Selectors.re which has selectors defined like:

let selectUser = (state) => state.user;

I am using the same selector in multiple components using:

let user = AppStore.Store.useSelector(Selectors.selectUser);

I tested memoization by adding a Js.Console.log in my selector and saw that it's called multiple times (I believe once per component that's rendered) without the state changing, then multiple times again every time the state changes.

So I tried memoizing my selectors with a cache with size=1:

/**
 * Memoize functions that depend on the appState. Works like memoize-one.
 */
let memoize = (f: (appState => 'a)): (appState => 'a) => {
  let lastState = ref(AppStore.initialState);
  let lastVal = ref(f(AppStore.initialState));

  (state) => {
    if (state === lastState^) {
      //Js.Console.log("cache hit");
      lastVal^;
    } else {
      //Js.Console.log("cache miss");
      lastState := state;
      lastVal := f(state);
      lastVal^;
    }
  }
};

let selectUser = memoize((state: appState) => state.user);

and now it correctly just runs the selectors once for each state update. I saw a React.useMemo2 in the code, so I thought a similar memoization was already implemented.

So unless I'm doing something wrong that's breaking memoization, getting this working would be an important performance improvement in this library!

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

1 participant