UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

17 lines (16 loc) 681 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); /** * Returns a state that changes only if the next value pass its validator */ var useValidatedState = function (validator, initialValue) { var _a = (0, react_1.useState)(initialValue), state = _a[0], setState = _a[1]; var validation = (0, react_1.useRef)({ changed: false }); var onChange = (0, react_1.useCallback)(function (nextValue) { setState(nextValue); validation.current = { changed: true, valid: validator(nextValue) }; }, [validator]); return [state, onChange, validation.current]; }; exports.default = useValidatedState;