Refs or references in React provide a way to access and interact with DOM nodes or React elements directly within your components. This is especially handy in cases where you want to change the child component without making use of props or triggering a re-render.
Refs are created by invoking the useRef
hook provided by React. Here's how we do it:
Notice that we call useRef()
without passing any arguments. This results in myRef.current
getting initialized with the value of null
. The current
property is mutable; it's created specifically for you to assign it a persistent value that doesn't trigger a re-render, thereby allowing the value to persist across renders.
Let’s see how the ref is used with an actual element in JSX by using the ref
attribute, which takes the ref created above as its value:
The ref
attribute acts like a tether, linking the myRef
ref to the input field, hence allowing us detailed access to this specific instance of the input field across renders. It lets myRef.current
point to the corresponding DOM node, here an HTMLInputElement, providing a way to read from or write to it.
Following is a brief example:
As we can see, the text input is now linked with nameRef
. Although in this form React does not automatically capture and update its value, opening up interesting possibilities we'll look at next.