ideas
ideas copied to clipboard
useDelay
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>;
}
Shouldn’t clearTimeout
get called when the component is unmounted?
Indeed. Thanks!