Skip to main content

useValidatedState

useValidatedState

A setState wrapper that performs some validation on any new state values.

Parameters

  • initialState - The initial state value to store.
  • validator - A validator function to check any new state values against before updating. The validator is expected to return either nothing, or a value of type E. If nothing is returned, the value is assumed to be valid and will be updated. If a value is returned, it will be set as the error value.

Returns

An array of:

  • The state value.
  • The current error value (defaults to null).
  • State setter function.

Example

const [state, error, setState] = useValidatedState(0, (value) => {
if (value < 0) {
return 'Value must be non-negative';
}
});

setState(-1); // error will be 'Value must be non-negative'
setState(1); // state will be updated to 1