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

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

this edge case: function SomeComponent({ foo }) { const refOne = ref => { // โ€ฆ } const refTwo = ref => { // โ€ฆ } return <div ref={foo ? refOne : refTwo} /> }

Because it's a new function each render unless wrapped in callback. Conditional rendering, making it based on props/outside variables etc. can easily change the logic on next render and React can't know when it's safe to call again and when it's not.

Same reason react calls useEffect every render unless a dep array is provided I guess. Realistically there's probably no use case for that, but unless we explicitly provide dep array (or useCallback for ref), React can't know when it should run the effect. So the safer bet is to call every render.