UNPKG

juln-hooks

Version:

juln 自己的 hooks 和 react-help 集合 (已完全支持 tree-shaking)

32 lines 1.39 kB
import { __read } from "tslib"; import { useState, useRef, useEffect, useCallback } from "react"; import { debounce, throttle } from "throttle-debounce"; var getUseThrottleOrDebounceState = function getUseThrottleOrDebounceState(mode) { if (mode === void 0) { mode = "debounce"; } var throttleOrDebounceFn = mode === "debounce" ? debounce : throttle; function useDebounceState(timestamp, initialState) { if (timestamp === void 0) { timestamp = 1000; } var realStateRef = useRef(typeof initialState === "function" ? initialState() : initialState); var _a = __read(useState(initialState), 2), debouncedState = _a[0], setDebouncedState = _a[1]; var setState = useCallback(function (valOrGetVal) { var newVal = typeof valOrGetVal === "function" ? valOrGetVal(realStateRef.current) : valOrGetVal; realStateRef.current = newVal; }, [realStateRef]); useEffect(function () { var cancel = throttleOrDebounceFn(timestamp !== null && timestamp !== void 0 ? timestamp : 1000, function () { return setDebouncedState(realStateRef.current); }).cancel; return cancel; }, [timestamp]); return [debouncedState, setState]; } return useDebounceState; }; export var useDebounceState = getUseThrottleOrDebounceState("debounce"); export var useThrottleState = getUseThrottleOrDebounceState("throttle");