Using Refs for More than DOM Access
Accessing DOM elements (for reading values) is one of the most common use cases for using refs. As shown above, it can help you reduce code in certain situations.
But refs are more than just "element connection bridges"; they are objects that can be used to store all kinds of values—not just pointers at DOM objects. You can, for example, also store strings or numbers or any other kind of value in a ref:
const passwordRetries = useRef(0);
You can pass an initial value to useRef()
(0
in this example) and then access or change that value at any point in time, inside of the component to which the ref belongs:
passwordRetries.current = 1;
However, you still have to use the current
property to read and change the stored value, because, as mentioned above, this is where React will store the actual value that belongs to the Ref.
This can be useful for storing data that should "survive" component re-evaluations...