Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Nirmal Rajendharkumar
To create a sleep function in React:
import {useEffect} from 'react'; const sleep = ms => new Promise( resolve => setTimeout(resolve, ms) ); const App = () => { const handleClick = async event => { console.log('start'); await sleep(1000); console.log('end'); }; useEffect(() => { async function fetchData() { console.log('start'); await sleep(1000); console.log('end'); } fetchData(); }); return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;
We created a sleep
function that waits for N milliseconds before returning.
const sleep = ms => new Promise( resolve => setTimeout(resolve, ms) );
The function takes the number of milliseconds as a parameter and uses the setTimeout method to wait for the specified number of milliseconds before resolving a Promise.
await
keyword or use the .then()
syntax.We marked the handleClick
function as async
, so we are able to use the
await
keyword in it.
const handleClick = async event => { console.log('start'); await sleep(1000); console.log('end'); };
The function logs start
to the console, then sleeps for 1
seconds and logs
end
.
The same approach can be used inside of the
useEffect hook but we
can't mark the function we pass to useEffect
as async
.
useEffect(() => { async function fetchData() { console.log('start'); await sleep(1000); console.log('end'); } fetchData(); });
Async functions return a Promise
object but the useEffect
hook can only
return a cleanup function, so we have to define our async function inside
useEffect
.