Skip to content

Instantly share code, notes, and snippets.

@alexboots
Created September 19, 2019 17:15
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 alexboots/4035c760e520762d36f1fe6ad079e30a to your computer and use it in GitHub Desktop.
Save alexboots/4035c760e520762d36f1fe6ad079e30a to your computer and use it in GitHub Desktop.
From docs:
“Any function inside a component, including event handlers and effects, “sees” the props and state from the render it was created in.”
so stale closures exist - you have to do like setCount(count => count + 1) to access the 'latest actual state'
if you do like setCount(count + 1) it wont increase because you're using the 'count' from the origional render
from here: https://overreacted.io/a-complete-guide-to-useeffect/
“Effects always “see” props and state from the render they were defined in. That helps prevent bugs but in some cases can be annoying. For those cases, you can explicitly maintain some value in a mutable ref.”
Can use refs to ignore this 'stale closures' issue since ref.current exists outside of the render:
```
function Timer() {
const [count, setCount] = React.useState(0)
const countRef = React.useRef(0)
React.useEffect(() => {
const intervalId = setInterval(() => {
countRef.current = countRef.current + 1
setCount(countRef.current)
}, 1000)
return () => clearInterval(intervalId)
}, [])
return (
<div>The count is: {count}</div>
)
}
```
from here:
https://leewarrick.com/blog/react-use-effect-explained/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment