Skip to content

Instantly share code, notes, and snippets.

@mahdiyazdani
Created June 21, 2021 20:29
Show Gist options
  • Save mahdiyazdani/cce3883c408a772a5381ee0327b120c4 to your computer and use it in GitHub Desktop.
Save mahdiyazdani/cce3883c408a772a5381ee0327b120c4 to your computer and use it in GitHub Desktop.
useWait React Hook
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