Skip to content

Instantly share code, notes, and snippets.

@nikgraf
Created July 21, 2022 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikgraf/5a22e4956dd9ded6c3a30637c7b2ba53 to your computer and use it in GitHub Desktop.
Save nikgraf/5a22e4956dd9ded6c3a30637c7b2ba53 to your computer and use it in GitHub Desktop.
Teaching useEffect
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