atlassian / react-sweet-state

Shared state management solution for React
https://atlassian.github.io/react-sweet-state/
MIT License
871 stars 55 forks source link

Hook getStore does not scale as parent containers grow #92

Closed albertogasparin closed 4 years ago

albertogasparin commented 4 years ago

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();
albertogasparin commented 4 years ago

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:

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