Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useDelay #52

Open
raunofreiberg opened this issue Oct 31, 2018 · 2 comments
Open

useDelay #52

raunofreiberg opened this issue Oct 31, 2018 · 2 comments

Comments

@raunofreiberg
Copy link

raunofreiberg commented Oct 31, 2018

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>;
}
@j-f1
Copy link

j-f1 commented Oct 31, 2018

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

@raunofreiberg
Copy link
Author

Indeed. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants