Post

unless refs changed while i wasn’t looking you need to wrap this in `useCallback`, otherwise it’ll call both the cleanup and setup function again every single render

Hmm isn't it the same as having a useEffect without dependency array, and then adding an empty one to it? That changes st which time / how often it runs.

What’s the use case for needing to run every render? Seems like a hacky way to do side effects in render

if you create it anonymously during render, react can’t know whether it’s actually the same function from the last render. so it cleans up the previous one and sets up the new one

I guess if I make a two-tweet post, it'll get easy to misinterpret it what I meant: if ref callbacks only ran once and used a value from state in a closure, it would use that value for its entire lifetime. subverting this is not idiomatic react

The video seems hung up on the wrong thing: many blog posts describe the problem with an incorrect analogy. Yet, "stale closure" is an apt description if you ignore the bad long-text blog description. Better would be "closure over a stale variable", but that would be unneccessarily long I guess.

I usually describe it like this: The callback holds a reference to the variable X at the time it was defined, and that variable will never be updated. Instead, a new variable also named X will be created in a future render with the new value, available to a new callback that also has the same name.

This is a really good video, thanks for sharing. I kinda disagree with the main point a bit: if the term wasn't used before 2019, why is it bad that meaning was given to it as a mental shortcut to a problem?

I feel a bit called out too because my blog is read in the video, but they missed the second part where I tried to explain that mutation is possible but uncommon in react. In the photo analogy (which I still like), this is the "photoshopping".

Ah sorry, it wasn't the point to call out, as I don't even remember his sources. I remember watching this a while back and I just recalled it! Please don't take this personally.