Create a hook to easily use setTimeout(callback, delay).
- reset the timer if delay changes
- DO NOT reset the timer if only callback changes
useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内持续存在。
export function useTimeout(callback: () => void, delay: number) {const callbackRef = useRef(callback)// your code hereuseEffect(() => {callbackRef.current = callback;},[callback])useEffect(() => {const id = setTimeout(() => {callbackRef.current()},delay)},[delay])}
