Created
June 21, 2021 20:29
-
-
Save mahdiyazdani/cce3883c408a772a5381ee0327b120c4 to your computer and use it in GitHub Desktop.
useWait React Hook
This file contains 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'; | |
import ReactDOM from 'react-dom'; | |
function useWait(delay) { | |
const [status, setStatus] = React.useState(false); | |
React.useEffect(() => { | |
const id = window.setTimeout(() => { | |
setStatus((c) => !c); | |
}, delay); | |
return () => window.clearTimeout(id); | |
}, [delay]); | |
return status; | |
} | |
function Wait({ delay = 1000, placeholder, ui }) { | |
const show = useWait(delay); | |
return show === true ? ui : placeholder; | |
} | |
function App() { | |
return ( | |
<div className="App"> | |
<Wait | |
delay={3000} | |
placeholder={<p> Waiting... </p>} | |
ui={<p> This text should appear after 3 seconds. </p>} | |
/> | |
</div> | |
); | |
} | |
const rootElement = document.getElementById('root'); | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment