Hook Master 🚀

useValidateState

Manages state with validation

Usage

useValidateState validates state with a given rule each time state is set. It returns an object with current validation state, last valid value and current value:

import { useValidatedState } from 'hook-master-react';
 
const [{ value, valid }, setValue] =
  useValidatedState('valid', (state) => state === 'valid');
 
value; // -> valid
valid; // -> true
 
setValue('invalid');
 
value; // -> invalid
valid; // -> false

Definition

function useValidatedState<T>(
  initialValue: T,
  validation: (value: T) => boolean,
  initialValidationState?: boolean
): [
  {
    value: T;
    valid: boolean;
  },
  (value: T) => void,
];

On this page