Created
February 25, 2021 11:03
-
-
Save codemzy/6551e64d50704e2a4b322cdd4412b625 to your computer and use it in GitHub Desktop.
React useDelay hook - to avoid flash of loading content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
// delay a state change (used for loading or waiting for async to avoid flash of loading state) | |
export default function useDelay(initial, { delay = 300, delayedValue = true, minDuration = 700 }) { | |
const [state, setState] = React.useState(initial); | |
const [change, setChange] = React.useState(initial); | |
const end = React.useRef(0); | |
React.useEffect(() => { | |
let timer; | |
let timeLeft = end.current - Date.now(); | |
if (change === delayedValue) { | |
// create a timer to only set the state if unchanged after the delay time | |
timer = setTimeout(function() { | |
setState(change); | |
end.current = Date.now() + minDuration; // record time that state can change again due to minDuration | |
}, delay); | |
} else if (timeLeft > 0) { | |
// create a timer to only change the state after the minDuration | |
timer = setTimeout(function() { | |
setState(change); | |
}, timeLeft); | |
} else { | |
setState(change); | |
} | |
// clean up | |
return function() { | |
timer && clearTimeout(timer); // clear any timeout | |
} | |
}, [change]); | |
return [state, setChange]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For use with loading state
For use with single status state