React refs and dom references
3 min read • Posted on August 21, 2020
Introduction
Sometimes you need to have access to a DOM element in React (like for focusing an input). To do so, React has a system of refs that you can use:
- with hooks:
- with classes:
Render lag
What I call “render lag” is the fact that refs that are bound to DOM elements will always be 1 render late: when doing ref={inputRef}
, react-dom attached the domElement once it is createdAt and added to DOM tree. So in order for the ref to be bound to the right DOM element, a render need to occur.
Which is why, if you want to safely use refs + dom nodes, you should only access them in methods that run after the renders (useEffect / useLayoutEffect / componentDidMount / componentDidUpdate).
But you shouldn’t read refs’ value directly within the render itself (render method / useMemo).
Illustration
Let’s say we are rendering an input and then dispatching one re-render, this is what will happen:
In most cases, domElement and domElement² are the same, but if you do something like this, it won’t be the case:
Conclusion
Refs can be a bit tricky to use but as long as we keep in mind that they should only be used in effects, it should be fine.
And if you really need to use the dom element in your render (like to trigger other effects), you may want to store it in a state: