cefn / watchable

Repo for @watchable/store and supporting packages.
MIT License
5 stars 1 forks source link

Introduce a usePartition hook #36

Open cefn opened 10 months ago

cefn commented 10 months ago

It's easy to incorrectly use partitions. You probably want a useStateProperty, which reads and writes to a single keyed property like React.useState rather than creating a whole store partition just for one property.

Given the overhead of a store structure and the potential memory leaks, it's easy to get partitions wrong in react. Creating a partition creates a long-lived listener on a store which you can't unsubscribe, and which has its own listener infrastructure. See https://github.com/cefn/watchable/issues/35 for how tempting using partitions looks.

For example this will create a new store every time the key changes, and they will just build up as listeners to the ancestor store, creating a memory leak.

export function usePartition<
  S extends Record<PropertyKey, unknown>,
  K extends keyof S
>(store: Store<S>, key: K) {
  return useMemo(() => createStorePartition(store, key), [store, key]);
}

As part of usePartition, perhaps a partition destroy() operation is needed that unsubscribes the partition and deliberately breaks all the operations which are no longer 'live' after unsubscribing. A usePartition hook would look after destroying partitions as well as creating them.