atlassian / react-sweet-state

Shared state management solution for React

Home Page:https://atlassian.github.io/react-sweet-state/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hook getStore does not scale as parent containers grow

albertogasparin opened this issue · comments

Current context getStore method recursively looks for the container of the same type through parent containers.
However that process is repeated on every re-render and even if it's a quite fast operation, we could easily tweak the implementation to traverse the parent containers only once, on initial render.
image

The way it could work is that context getStore does not return directly the store state, but a method to get that store state from the container that holds it (we can assume that such container will hold the state for the entire lifetime of the hook, given adding/removing parent containers will trigger an unmount).
Then we can cache such method and call that one on every render.

const { findStoreGetter } = useContext(Context);
const { current: getStore } = useRef(findStoreGetter(Store));
const { storeState, actions } = getStore();

While it might be annoying to see, couldn't prove any real performance difference when memoizing the store getter.
The reason probably lies on the fact that:

  • getStore is extremely performant: just two dumb conditionals before calling the parent getStore
  • by using useMemo (useRef won't do) the burden of creating a new function on every render and checking the array of dependencies nullifies the possible gains

So even if we see dozens of those getStore calls in the profiler, when it comes down to time spent I could not find any difference in the component render time (even with 50 levels of containers at 6x slowdown and on dev mode).

Parking this for now