Home > Net >  Refactor a custom hook to be called inside a method
Refactor a custom hook to be called inside a method

Time:09-08

I created this hook that is responsible to do something after an amount of time:

const useTime = (callback, timeout = 1000) => {
    useEffect(() => {
        const timer = setTimeout(() => {
            callback()
        }, timeout);
        return () => clearTimeout(timer);
    }, []);
}

The hook is working, but i can not call it inside a method like:

  {        
  clear: () => {
    useTime(() => console.log('close'), 6000 )
  },

... this is happen because of hooks rules.
Question: How to refactor the hook to be able to call it inside a method or a function?

CodePudding user response:

You probably need to do like this -

function useTime(cb, timeout = 100) {
  const timer = setTimeout(() => {
     cb();
  }, timeout);

  return () => clearTimeout(timer);
}

function anotherMethod() {
  const cancel = useTime(runJob, 1000);
  
  // if you wanna cancel the timer, just call the cancel function
  cancel();
}

CodePudding user response:

You can try something around this:

const useTime = () => {
    const timer = useRef();
    const fn = useCallback((callback, timeout = 1000) => {
      timer.current = setTimeout(() => {
        callback()
      }, timeout);
    }, []);

    useEffect(() => {
        return () => clearTimeout(timer.current);
    }, []);

    return fn;
}
  const delayedFn = useTime();

  clear: () => {
    delayedFn(() => console.log('close'), 6000)
  },

Edit crimson-water-7i9etg

  • Related