How to use useRef in React
Using useRef is essential for accessing DOM elements directly, storing mutable values, and integrating with third-party libraries in React applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented useRef in countless React components for focus management, scroll positioning, and integrating with non-React libraries in enterprise applications. From my expertise, the most effective approach is to use useRef for DOM references and persistent value storage. This method provides direct DOM access without causing re-renders, making it perfect for imperative operations and performance-critical scenarios.
Use useRef
hook to create references for DOM elements and mutable values that persist across renders.
import { useRef, useEffect } from 'react'
function TextInput() {
const inputRef = useRef(null)
const renderCount = useRef(0)
useEffect(() => {
// Focus input on mount
inputRef.current.focus()
// Increment render count without causing re-render
renderCount.current += 1
})
const handleFocus = () => {
if (inputRef.current) {
inputRef.current.focus()
}
}
return (
<div>
<input ref={inputRef} type="text" placeholder="Enter text" />
<button onClick={handleFocus}>Focus Input</button>
<p>Render count: {renderCount.current}</p>
</div>
)
}
The useRef
hook returns a mutable ref object with a .current
property that persists across component re-renders. For DOM references, attach the ref to an element using the ref
attribute. Access the DOM element through ref.current
to call methods like focus()
, scrollTo()
, or get properties. Use useRef to store mutable values that don’t trigger re-renders when changed, unlike useState. This is perfect for timers, previous values, or integration with imperative libraries.
Best Practice Note:
This is the same approach we use in CoreUI React components for focus management and third-party library integration.
Always check if ref.current
exists before using it, use refs sparingly (prefer declarative patterns), and consider forwardRef
for passing refs through component hierarchies to child elements.