A few weeks ago, I talked about closures in JavaScript because it’s a concept that is frequently asked in technical interviews. But closures are not just an interview topic. They are used all the time in real applications — including React. A good example is React’s useState hook. In the simplified example in the image, both functions returned from the outer function still have access to the same `state` variable. Even though the outer function has already finished executing, those inner functions "remember" the environment where they were created. That’s exactly what a closure is. This is the core idea React relies on to preserve state between renders: functions that still have access to values created earlier. Of course, React’s real implementation is more complex, but the underlying concept is the same. Understanding these fundamentals makes React hooks feel much less like magic, and shows how many of the frameworks and libraries we use every day are built on top of simple JavaScript concepts. #React #JavaScript #Frontend #WebDevelopment #SoftwareEngineering
"Stale closures" on React are a misnomer, its just how react behaves to batch the state changes and optimize re-renders. Stale closures are not the issue. The entire conversation I think is a huge nit, but I find it is an interesting topic nonetheless. The video for those who are curious: https://www.youtube.com/watch?v=7yw_D3h4xSo
This is a great explanation. Closures are one of those concepts that seem abstract at first, but once you see how they’re used in things like useState, everything starts to click. It really shows how many “advanced” patterns in React are built on top of core JavaScript fundamentals. Understanding this definitely makes hooks feel a lot less like magic.
Closures always gives me a knot on the brain. ahah But they are beautiful when we sit down, relax and look well at them. 😍
That’s actually a misconception of how useState() works. It doesn’t remember between renders with closures — they’re stored and looked up in React’s “fiber,” which (as far as I know) is a big linked list type of thing that lives outside the component. Preserving state via closure wouldn’t work anyway since they’re called fresh on every render. Still good concept to know, but not really how React uses it.