Create a hook to easily use setTimeout(callback, delay).

  1. reset the timer if delay changes
  2. DO NOT reset the timer if only callback changes

    useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内持续存在。

    1. export function useTimeout(callback: () => void, delay: number) {
    2. const callbackRef = useRef(callback)
    3. // your code here
    4. useEffect(() => {
    5. callbackRef.current = callback;
    6. },[callback])
    7. useEffect(() => {
    8. const id = setTimeout(() => {
    9. callbackRef.current()
    10. },delay)
    11. },[delay])
    12. }