jotaijs / jotai-scope

MIT License
55 stars 4 forks source link

New store reference being created each render #13

Closed fredrikjacobson closed 10 months ago

fredrikjacobson commented 10 months ago

Hi, I'm facing issues when using ScopeProvider together with useHydrateAtoms

I'm running jotai-scope 0.4

I believe it has to do with the patching of the store. https://github.com/jotaijs/jotai-scope/blob/c80013b11da21c1bf2cc05edaf0fa0ece637e022/src/ScopeProvider.tsx#L76C1-L81

If I understand correctly the new fix with patching store will end up creating new stores each render. I noticed since using useHydrateAtoms would trigger several times and my const hydratedMap would grow when looking in the debug tools.

Taking a look at #10, this seems aimed at solving the same problem, with much of the same considerations around a stable atom list and re-renders.

Use case

In terms of use case, our specific use case is where we replace part of the render tree (the main layout) while keeping other parts of the UI such as sidebar, topbar etc. This means the ScopeProvider is still susceptible to re-renders.

fredrikjacobson commented 10 months ago

Naively wrappning the patched store in useMemo appears to work. but also needs the scopedGetters to be memoized together with

  const store = useStore();
  const patchedStore: typeof store = useMemo(
    () => ({
      ...store,
      get: (anAtom, ...args) => store.get(getScopedAtom(anAtom), ...args),
      set: (anAtom, ...args) => store.set(getScopedAtom(anAtom), ...args),
      sub: (anAtom, ...args) => store.sub(getScopedAtom(anAtom), ...args),
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [store],
  );

In addition, I suppose we need to store the mapping and atomSet with some reference, since they can't be recreated on each render. useMemo could work for atomSet but would require the atoms list to be stable.

dai-shi commented 10 months ago

Can you try https://ci.codesandbox.io/status/jotaijs/jotai-scope/pr/10/builds/432670 ? See "Local Install Instructions".

fredrikjacobson commented 10 months ago

Can you try https://ci.codesandbox.io/status/jotaijs/jotai-scope/pr/10/builds/432670 ? See "Local Install Instructions".

It did solve my use case of useHydrateAtoms, which should also mean the store does not get re-created on each render.

Thanks!

dai-shi commented 10 months ago

https://www.npmjs.com/package/jotai-scope/v/0.4.1 is published.