Skip to content

Instantly share code, notes, and snippets.

@kgnadinger
Last active March 14, 2019 09:56
Show Gist options
  • Save kgnadinger/9bd70cf5cf911c1b0edf8dbdb631beeb to your computer and use it in GitHub Desktop.
Save kgnadinger/9bd70cf5cf911c1b0edf8dbdb631beeb to your computer and use it in GitHub Desktop.
function App({ name }) {
// stateHook that keepts track of the count with initial count = 0
const [count, setCount] = useState(0);
// get the latest count (not the count scoped inside this function)
const latestCount = useRef(count);
// is called for every render and sees the variable states for this particular render
useEffect(() => {
// count is scoped to this render
document.title = `The count in this render is: ${count}`
/*
Clean up phase, any variables passed to it are scoped for this particular render, not the latest.
The order is also a little off. Example of 2 render cycles:
- Render 1 paints
- Render 1 calls useEffect
- Render 2 paints
- Render 1 cleans up
- Render 2 calls useEffect
*/
return () => {
console.log("Clean up count: ", count)
}
// Tells React to only run useEffect when count changes from one render to the next
}, [count]);
// An example of a useEffect that only runs once
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'http://api.mydomain.com?q=some_query',
);
console.log("Result Data: ", result.data);
};
fetchData();
/*
Because the array is empty, on the second render, React will not re-run this effect.
This is because the array contents have not changed
*/
}, []);
return (
// shows the count scoped inside this render
<p> You clicked {count}times</p>
// increments the count
<button onClick = {
() => setCount(count + 1)
}> Click me </button>
<button onClick = {
() => {
/*
Alerts the latest count, not necessarily the one scopped inside this render.
If the first button is hit several times in succession, the alert will show the current count after 5 seconds but not necessarily
the count inside this render cycle.
*/
setTimeout(() => {
alert("The latest count: " + latestCount.current);
}, 5000);
}
}> Show alert < button >
)
}
@jcampuza
Copy link

👍 Only thing missing is that AFAIK in the set timeout you have it should instead be the following

alert("The latest count: " + latestCount.current);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment