mirror of
https://github.com/usememos/memos.git
synced 2025-06-05 22:09:59 +02:00
@ -1,4 +1 @@
|
||||
export * from "./useDebounce";
|
||||
export * from "./useLoading";
|
||||
export * from "./useTimeoutFn";
|
||||
export * from "./useToggle";
|
||||
|
@ -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];
|
||||
}
|
@ -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];
|
||||
}
|
@ -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;
|
Reference in New Issue
Block a user