ahooks
Version:
react hooks library
26 lines (25 loc) • 819 B
JavaScript
import { useCallback, useState } from 'react';
import useLatest from '../useLatest';
import { isFunction } from '../utils';
function useEventTarget(options) {
const { initialValue, transformer } = options || {};
const [value, setValue] = useState(initialValue);
const transformerRef = useLatest(transformer);
const reset = useCallback(() => setValue(initialValue), []);
const onChange = useCallback((e) => {
const _value = e.target.value;
if (isFunction(transformerRef.current)) {
return setValue(transformerRef.current(_value));
}
// no transformer => U and T should be the same
return setValue(_value);
}, []);
return [
value,
{
onChange,
reset,
},
];
}
export default useEventTarget;