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 useStateProperty Hook #37

Closed
cefn opened this issue Nov 4, 2023 · 1 comment · Fixed by #40
Closed

Introduce a useStateProperty Hook #37

cefn opened this issue Nov 4, 2023 · 1 comment · Fixed by #40

Comments

@cefn
Copy link
Owner

cefn commented Nov 4, 2023

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 #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
Copy link
Owner Author

cefn commented Nov 6, 2023

Closed by #40

@cefn cefn closed this as completed in #40 Nov 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant