Borislav Hadzhiev
Mon May 02 2022·2 min read
Photo by Kinder Land
To create a delay function in React:
setTimeout
method to resolve a Promise after the provided number of
milliseconds.import {useEffect} from 'react'; const delay = ms => new Promise( resolve => setTimeout(resolve, ms) ); const App = () => { const handleClick = async event => { console.log('before'); await delay(1000); console.log('after'); }; useEffect(() => { async function makeRequest() { console.log('before'); await delay(1000); console.log('after'); } makeRequest(); }); return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;
We created a delay
function that waits for N milliseconds before resolving a
Promise.
const delay = 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
the result 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('before'); await delay(1000); console.log('after'); };
The function logs before
to the console, then waits for 1
seconds and logs
after
.
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('before'); await delay(1000); console.log('after'); } 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
.