ideas icon indicating copy to clipboard operation
ideas copied to clipboard

useDelay

Open raunofreiberg opened this issue 6 years ago • 2 comments

Useful for delaying the render of a component on mount (and optionally executing a callback after the delay). I use this for a chatbot application in my own code.

function useDelay(ms = 1000, callback = () => {}) {
  let timeoutId;
  const [hasExpired, setExpired] = useState(false);

  useEffect(() => {
    timeoutId = setTimeout(
      () => {
        setExpired(true);
        callback();
        clearTimeout(timeoutId);
      }, 
      ms
    );
  }, []);

  return hasExpired;
}

Usage example:

function Delay() {
  const hasExpired = useDelay(5000, () => {
    console.log("Callback after delay");
  });
  return <div>{hasExpired ? "Expired" : "Loading..."}</div>;
}

raunofreiberg avatar Oct 31 '18 14:10 raunofreiberg

Shouldn’t clearTimeout get called when the component is unmounted?

j-f1 avatar Oct 31 '18 20:10 j-f1

Indeed. Thanks!

raunofreiberg avatar Nov 01 '18 11:11 raunofreiberg