|
|
|
|
|
by Stoids
2689 days ago
|
|
Perhaps I'm just a bit dumb here, but a few of these comments confused me. > However, this is a common source of mistakes if you’re not very familiar with JavaScript closures. > The problem is that useEffect captures the count from the first render. It is equal to 0. We never re-apply the effect so the closure in setInterval always references the count from the first render, and count + 1 is always 1. Oops! Perhaps I'm not understanding the second comment fully... This behavior is completely counter to how Javascript closures work in my mental model. I'm trying to figure out how a state hook differs in execution from a normal variable in module scope. How does it differ from this [1] example. [1] https://jsfiddle.net/xuz09cow/1/ |
|
Your code avoids the closure problem, but closedVariable would be more like a static variable — it'd be shared by every instance of the hook. Probably not what you intended!