rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
40 lines (39 loc) • 1.25 kB
JavaScript
import { useState, useEffect, useCallback } from "react";
var defaultOptions = {};
/**
*
* useInput Hook
*
* Handles an input's value and onChange props internally to
* make text input creation process easier
*
* @param {unknown} [initialValue] Initial value of the input
* @param {Options} [options] Options object
* @returns {InputHandler} Input handler with value and onChange
* @see https://react-hooks.org/docs/useInput
*/
function useInput(initialValue, options) {
if (initialValue === void 0) { initialValue = ""; }
if (options === void 0) { options = defaultOptions; }
var _a = useState(initialValue), value = _a[0], setValue = _a[1];
var onChange = useCallback(function (event) {
var newValue = event.target.value;
var shouldUpdate = true;
if (typeof options.validate === "function") {
shouldUpdate = options.validate(newValue, value);
}
if (shouldUpdate) {
setValue(newValue);
}
}, [options, value]);
// sync with default value
useEffect(function () {
setValue(initialValue);
}, [initialValue]);
var handler = {
onChange: onChange,
value: value,
};
return handler;
}
export { useInput };