Created
July 21, 2022 10:43
-
-
Save nikgraf/5a22e4956dd9ded6c3a30637c7b2ba53 to your computer and use it in GitHub Desktop.
Teaching useEffect
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 { useEffect, useRef, useState } from "react"; | |
function App() { | |
const [counter, setCounter] = useState(3); | |
console.log("App render", counter); | |
useEffect(() => { | |
console.log("App Effect"); | |
// console.log("App Effect", counter); | |
return () => { | |
// the state is still from the previous render | |
console.log("App Effect Cleanup"); | |
// console.log("App Effect Cleanup", counter); | |
}; | |
}); | |
// Quiz: When does the cleanup function run? | |
// | |
// App render (initial render) | |
// App Effect (initial render Effect) | |
// -> click and update state | |
// | |
// A: | |
// App Render | |
// App Effect | |
// | |
// B: | |
// App Effect Cleanup | |
// App Render | |
// App Effect | |
// | |
// C: | |
// App Render | |
// App Effect Cleanup | |
// App Effect | |
return ( | |
<div> | |
<h1>Hello World</h1> | |
{counter} | |
<button | |
onClick={() => { | |
setCounter((prevCounter) => prevCounter + 1); | |
}} | |
> | |
+1 | |
</button> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment