Skip to content

useSelector not memoized? #68

@froatsnook

Description

@froatsnook

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions