cefn / watchable

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

Introduce a useStateProperty Hook #37

Closed cefn closed 9 months ago

cefn commented 10 months ago

To parallel the signature of a useState hook, it would make sense to add useStateProperty which composes a value and a setter. This would guide people away from using partitions which might otherwise seem like a worthwhile approach (but has complexity and overhead when you didn't actually want to compose a whole new long-lived store). See https://github.com/cefn/watchable/issues/35

A draft implementation would be this...

export function useStateProperty<
  S extends Record<PropertyKey, unknown>,
  K extends keyof S
>(store: Store<S>, key: K) {
  const setter = useCallback(
    (value: S[K]) => {
      store.write({
        ...store.read(),
        [key]: value,
      });
    },
    [store, key]
  );
  const selector = useCallback((state: Immutable<S>) => state[key], [key]);
  const value = useSelected(store, selector);
  return [value, setter] as const;
}
cefn commented 9 months ago

Closed by https://github.com/cefn/watchable/pull/40