37. Refs (useRef)
Escaping the Render Cycle
In React, we typically use useState to store data. However, updating state always triggers a component re-render. What if you need to store a value and update it, but you do not want to trigger a re-render? Or what if you need to bypass React entirely and physically touch an HTML DOM element? This is exactly what useRef is for.
Storing Mutable Values
The useRef hook returns a mutable object with a single property: .current. You can change this value freely without causing a render. It is perfect for storing background data like timer IDs or previous state values.
Accessing DOM Elements Directly
React generally discourages direct DOM manipulation (like using document.getElementById). But sometimes it is unavoidable, such as when you need to manually focus an input field, measure an element's physical width, or integrate with a non-React library (like a 3D canvas). You attach a ref to an element using the special ref prop.
Forwarding Refs
If you build a custom component (like <CustomInput />) and a parent component tries to pass a ref to it, React will throw an error. By default, custom components don't expose their internal DOM nodes. You must wrap your custom component in forwardRef to allow the ref to pass through.
Knowledge Check
Ready to test your understanding of 37. Refs (useRef)?