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

usePropState (TypeScript) #25

Closed
mellson opened this issue Feb 16, 2019 · 1 comment
Closed

usePropState (TypeScript) #25

mellson opened this issue Feb 16, 2019 · 1 comment

Comments

@mellson
Copy link

mellson commented Feb 16, 2019

How do you feel about adding typescript to useHooks?

For instance I am working on this setState wrapper which allows a typesafe way to set a property of the state:

import { Dispatch, SetStateAction, useState } from 'react';

/**
 * This hook is a supplement to setState - https://reactjs.org/docs/hooks-state.html
 * It let's you update a property of the state in a typesafe way.
 *
 * @param initialState - the initial state for this hook, it is forwared to useState
 *
 * @returns
 * [state, setPropState, setState]
 * state is the state returned from the useState hook.
 * setPropState is the typesafe function for updating a part of the state.
 * setState is the normal setState function for setting the entire state at once.
 */
export const usePropState = <T>(
  initialState: T
): [T, <K extends keyof T>(part: K) => (value: T[K]) => void, Dispatch<SetStateAction<T>>] => {
  const [state, setState] = useState(initialState);

  const setPropState = <K extends keyof T>(part: K) => (value: T[K]) => {
    setState({ ...state, [part]: value });
  };

  return [state, setPropState, setState];
};

@gragland
Copy link
Contributor

Thanks for sharing! I think I want to avoid TypeScript for now to keep things as simple as possible. A lot of people are still learning hooks and I want to avoid introducing extra concepts. At some point if I do an example that composes useState in a simple way (like maybe useMergedState) I could add this example to the links section.

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

No branches or pull requests

2 participants