Created
July 20, 2021 02:04
-
-
Save dylan-albertazzi/d8a6016606e2e77c408191bbf73da36f to your computer and use it in GitHub Desktop.
Stop useEffect Hook React re-render multiple times with Async Await | Dylan Albertazzi YouTube
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, { useState, useEffect } from "react"; | |
function App() { | |
const [value, setValue] = useState(""); | |
//Waits for a period of time then resolves | |
function timeout(ms) { | |
return new Promise((resolve) => setTimeout(resolve, ms)); | |
} | |
useEffect(() => { | |
let isCancelled = false; | |
const handleChange = async () => { | |
//const data = await getdata() | |
await timeout(1000); | |
if (!isCancelled) { | |
alert(`A name was changed: ${value}`); | |
} | |
}; | |
handleChange(); | |
//Cleanup function is called when useEffect is called again or on unmount | |
return () => { | |
isCancelled = true; | |
}; | |
}, [value]); | |
return ( | |
<div className="App"> | |
<div> | |
<form> | |
<label> | |
Name: | |
<input | |
type="text" | |
value={value} | |
onChange={(event) => setValue(event.target.value)} | |
/> | |
</label> | |
<input type="submit" value="Submit" /> | |
</form> | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment