DEV Community

Discussion on: Avoiding useEffect with callback refs

Collapse
 
tkdodo profile image
Dominik D

But you also said this is a "good example", and it isn't:

I said:

A good example where you might need a ref is focus management.

And it is! Focus management is so much more than "autofocus". Please read the attached RFC: github.com/devongovett/rfcs-1/blob...

To achieve this, you need refs at the moment. I merely picked "autofocus" because it's a cheap way to show a side-effect, and it's also what the react beta docs use to show how to programmatically focus a node:

beta.reactjs.org/learn/manipulatin...

And I added the paragraph to avoid discussion about "just use the autofocus attribute" 😅


I like the useBoundingClientRect hook example. I'm pretty sure it will still use "callback refs" because you'll likely attach the setElement function to your react element via a ref?

const [rect, setElement] = useBoundingClientRect()

<div ref={setElement} />
Enter fullscreen mode Exit fullscreen mode

this approach also uses "callback refs" - it's just that the whole dom node is stored in react state :)