Omnistac / zedux

:zap: A Molecular State Engine for React
https://Omnistac.github.io/zedux/
MIT License
376 stars 7 forks source link

fix: optimize `useAtomSelector` for React 19 #106

Closed bowheart closed 3 months ago

bowheart commented 3 months ago

Description

useAtomSelector has had to jump through so many hoops to support React 18. Some of these hoops have caused such ugly code that edge cases are possible. We've seen one that we can't reproduce consistently, but it comes down to React scheduling useEffect microtasks for a newly mounted component tree at different points in time that interweave with useAtomSelector's queueMicrotask calls inside its useEffects in that same component tree.

useAtomSelector has to support React StrictMode (and concurrent mode and everything StrictMode prepares for) while handling inline selectors, selectors that return referentially unstable results, and of course the old problematic React behavior of unmounting a component tree after the new tree has rendered, but before its effects have run.

This is fairly difficult. But two underlying React issues in StrictMode (and only StrictMode - concurrent mode is fine) made it just ridiculous:

These made tracking down selector cache entries created for inline selectors on that initial render an impossible task to do perfectly. We had to put some hacky workarounds together to prevent memory leaks. These hacky workarounds included the problematic queueMicrotask in a useEffect that reads data off the Zedux ecosystem (something that does persist between renders) to try to clean up leaked selector caches from inline selectors whose references changed on the second render. Anyway, it was a nightmare. But:

This nightmare is no more! React 19 fixes both these underlying issues - refs are stable even in StrictMode and useId returns a consistent id even on initial render.

So clean up useAtomSelector a ton. Get rid of the ignorePhase state machine, the queueMicrotasks, ecosystem.selectors._storage, and the deferring graph edge creation until the useEffect runs. Go back to the good old ref swapping for inline selectors to prevent unnecessary graph updates. Update tests and double check all of them.

What This Means for You

We're releasing this change under Zedux v1.3.0-rc.x. This change is compatible with React 18 non-StrictMode only.