How to use refs to access DOM elements in React

Using refs to access DOM elements enables direct manipulation when React’s declarative paradigm isn’t sufficient for specific use cases. As the creator of CoreUI with over 11 years of React development experience, I’ve used refs extensively for integrating third-party libraries, managing focus, and implementing complex interactions. From my expertise, the most effective approach is using the useRef hook to create persistent references that survive component re-renders. This technique provides imperative access to DOM elements while maintaining React’s component lifecycle.

Use the useRef hook to create references for accessing DOM elements directly in functional components.

import { useRef, useEffect } from 'react'

function MyComponent() {
  const inputRef = useRef(null)

  useEffect(() => {
    inputRef.current.focus()
  }, [])

  return <input ref={inputRef} type='text' />
}

Here useRef(null) creates a mutable ref object that persists across renders. The ref={inputRef} attribute attaches the DOM element to the ref, making it accessible via inputRef.current. In the useEffect, inputRef.current.focus() directly calls the DOM focus method. This pattern is essential for focus management, scroll positioning, canvas operations, and third-party library integration where imperative DOM access is required.

Best Practice Note:

This is the same approach we use in CoreUI React components for managing focus states, integrating charting libraries, and implementing complex UI interactions. Use refs sparingly and prefer React’s declarative patterns when possible - refs are best for cases where declarative solutions aren’t feasible.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author