0.0.14 • Published 2 years ago
@jrop/hooks v0.0.14
@jrop's React Hooks
useAsync
useControlled
function useControlled<T>(prop: T|undefined, initialValue: T|(() => T), onChange?: (x: T) => any)
A handy utility for creating optional prop-controlled components. Uses React.useState, internally.
For example:
const MyTextInput = (props: {value?: string, onValueChanged?: (newValue: string) => any}) => {
  const [value, setValue] = useControlled(props.value, "", props.onValueChanged);
  // any calls to setValue will automatically call onValueChanged
  // will work for controlled/uncontrolled mode (i.e., whether or not props.value is provided)
  // ...
}useControlledReducer
function useControlledReducer<A, T>(prop: T|undefined, initialValue: T|(() => T), reducer: (prevState: T, action: A) => T, onChange?: (x: T) => any)
A handy utility for creating optional prop-controlled components. Uses React.useReducer, internally.
For example:
const MyTextInput = (props: {value?: string, onValueChanged?: (newValue: string) => any}) => {
  const [value, dispatch] = useControlledReducer(props.value, "", (_state, action: string) => action, props.onValueChanged);
  // any calls to dispatch will automatically call onValueChanged
  // will work for controlled/uncontrolled mode (i.e., whether or not props.value is provided)
  // ...
}useMounted
function useMounted(): boolean
Returns whether the component is mounted.
usePopup
useWrappedCallback
function useWrappedCallback<F extends Function>(f: F): F
Wraps a function whose identity does not change across re-renders. That is, for:
const fn = useWrappedCallback(() => {});...fn will always be the same reference.