chore: add react use (#2157)

* chore: add react use

* chore: update
This commit is contained in:
boojack
2023-08-21 02:35:53 +08:00
committed by GitHub
parent 19e7731abb
commit b9b795bf0e
16 changed files with 149 additions and 283 deletions

View File

@ -1,4 +1 @@
export * from "./useDebounce";
export * from "./useLoading";
export * from "./useTimeoutFn";
export * from "./useToggle";

View File

@ -1,12 +0,0 @@
import { DependencyList, useEffect } from "react";
import useTimeoutFn from "./useTimeoutFn";
export type UseDebounceReturn = [() => boolean | null, () => void];
export default function useDebounce(fn: () => any, ms = 0, deps: DependencyList = []): UseDebounceReturn {
const [isReady, cancel, reset] = useTimeoutFn(fn, ms);
useEffect(reset, deps);
return [isReady, cancel];
}

View File

@ -1,40 +0,0 @@
import { useCallback, useEffect, useRef } from "react";
export type UseTimeoutFnReturn = [() => boolean | null, () => void, () => void];
export default function useTimeoutFn(fn: () => any, ms = 0): UseTimeoutFnReturn {
const ready = useRef<boolean | null>(false);
const timeout = useRef<ReturnType<typeof setTimeout>>();
const callback = useRef(fn);
const isReady = useCallback(() => ready.current, []);
const set = useCallback(() => {
ready.current = false;
timeout.current && clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
ready.current = true;
callback.current();
}, ms);
}, [ms]);
const clear = useCallback(() => {
ready.current = null;
timeout.current && clearTimeout(timeout.current);
}, []);
// update ref when function changes
useEffect(() => {
callback.current = fn;
}, [fn]);
// set on mount, clear on unmount
useEffect(() => {
set();
return clear;
}, [ms]);
return [isReady, clear, set];
}

View File

@ -1,21 +0,0 @@
import { useCallback, useState } from "react";
// Parameter is the boolean, with default "false" value
const useToggle = (initialState = false): [boolean, (nextState?: boolean) => void] => {
// Initialize the state
const [state, setState] = useState(initialState);
// Define and memorize toggler function in case we pass down the component,
// This function change the boolean value to it's opposite value
const toggle = useCallback((nextState?: boolean) => {
if (nextState !== undefined) {
setState(nextState);
} else {
setState((state) => !state);
}
}, []);
return [state, toggle];
};
export default useToggle;