saasquatch / bunshi

Molecule pattern for jotai, valtio, zustand, nanostores, xstate, react and vue
https://www.bunshi.org/
MIT License
218 stars 16 forks source link

Inconsistent behavior when unmounting/remounting components (Not StrictMode) #65

Open HBake opened 4 months ago

HBake commented 4 months ago

Reproduction on Stackblitz

https://stackblitz.com/edit/vitejs-vite-v9qnbh?file=src%2Fmain.tsx

Possibly related to #58 and/or #64

I am aware of the workaround of using the molecule in a root component. I want the molecule to be unmounted if I visit a different route that doesn't use it instead though.

Edit: Here's a simpler reproduction with no react-router https://stackblitz.com/edit/vitejs-vite-pqhs2r?file=src%2Fmain.tsx

loganvolkers commented 4 months ago

Edit: Here's a simpler reproduction with no react-router https://stackblitz.com/edit/vitejs-vite-pqhs2r?file=src%2Fmain.tsx

This simpler reproduction is related to #58 more than #64.

Since there is a brief time when the previous component is unmounted before a new component is mounted, this is expected behaviour. There's nothing that can hold onto the value of the molecule between renders.

Unless MyComponent1 and MyComponent2 both are alive at the same time, there's no way in React to extend the lease for the molecule value between them.

image

HBake commented 4 months ago

I see, thanks for the explanation. It seems my "simpler reproduction" was a separate issue from the original.

I don't think the behavior in the first StackBlitz is explained by this image because most of the link-switch types work without unmounting the molecule

Edit: I'm not positive about this, but it seems as if during the navigation, molecules don't keep their dependent molecules cached/alive. Molecules mounted with useMolecule by the new component are preserved, while molecules mounted with mol are forgotten.