Why use REF instead of state for handling focus?

(Tor Ranfelt) #1

I have found many sites (like https://reactjs.org/docs/refs-and-the-dom.html) that say it is okay to use REF instead of state for handling focus, and that it is one of the core reasons for the existence of REF. But why/when is it better than using state?

(Simon Williams) #2

It’s not possible to use state to control focus. There isn’t any React API for this, because it’s not controlled by React - it’s controlled by the DOM, which only allows one component to have focus at a time.

If you had a hasFocus boolean prop you could pass to say if a component has focus or not, this could lead to inconsistencies. What happens if your state says two components have focus?

<input hasFocus={ true } />
<input hasFocus={ true } />

More broadly speaking, refs are ok to use when you can’t use state for some reason. Usually because that state is controlled by the DOM or another API.

It might be valid for React components to sometimes hide state internally, with limited methods to manipulate it (for example, only providing a clear() method). However, you should think very carefully about this before doing it.

(Tor Ranfelt) #3

Thanks for the clear explanation.