mutik icon indicating copy to clipboard operation
mutik copied to clipboard

Migrate to useSyncExternalStore, make typesafe

Open zephraph opened this issue 2 years ago • 2 comments

Fixes #25

Okay, so... this turned into a whole thing. It's a breaking change but worth it in my opinion.

As I mentioned in #25, there's a new API called useSyncExternalStore which replaces useMutableSource with a few benefits. One benefit is the whole source part goes away. This is particularly interesting for mutik, because it means we can essentially do away with the Provider wholesale. To get the typing right and to ensure useSelector (now useStore, more on that in a second) has access to the store I've turned createStore into a function that returns both the store and the hook to access it.

Usage is something like this:

const [store, useStore] = createStore({ count: 0 });

One of the new things with the useSyncExternalStore is that selectors aren't required to be memoized. From my understanding, with useMutableSource essentially you'd resubscribe to the store every time the selector changed. useSyncExternalStore on the other hand has dedicated support for selectors... hell, it even memoizes getSnapshot for us! The net result is a far simpler/smaller implementation.

The last bit of cool news: useSyncExternalStore is going to be released in React v18 but it also is being published in use-sync-external-store and will be backwards compatible with all hooks versions. I set the React version to the latest v16. No more experimental react installs!

zephraph avatar Sep 10 '21 04:09 zephraph

You'll likely need #26 to get the example to work. I did at least.

zephraph avatar Sep 10 '21 05:09 zephraph

🎉

damassi avatar Sep 17 '21 07:09 damassi