Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce a usePartition hook #36

Open
cefn opened this issue Nov 4, 2023 · 0 comments
Open

Introduce a usePartition hook #36

cefn opened this issue Nov 4, 2023 · 0 comments
Labels
store-react Related to @watchable/store-react

Comments

@cefn
Copy link
Owner

cefn commented Nov 4, 2023

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 #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
store-react Related to @watchable/store-react
Projects
None yet
Development

No branches or pull requests

1 participant