What is useRef in React? What are the use cases of useRef?

What is useRef?

useRef() is a built-in React hook. This hook accepts one argument as the initial value and returns a reference (known as ref). The reference is the object having a special property current.

Example of useRef:

import React, { useRef } from 'react';

function App() {
    const reference = useRef(false);

    const clickHandler = () => {
        if(!reference.current) {
            // Do the necessary tasks
            reference.current = true;
        }
    };
}

Important notes about useRef:

  • When we update the reference of useRef, the component does not re-render
  • The value of the reference remains the same between component re-rendering

Following is a use case of useRef built-in hook:

Accessing DOM elements:

import React, {useRef, useEffect} from 'react';
/*
 * Purpose: The purpose of this component is the ref output.
 *
 * Version: 1.0
 */

const Ref = () =>{

  const elementRef = useRef();

  useEffect(() => {
    const divElement = elementRef.current;
    console.log(divElement.classList.item(0));
  }, []);

  return (
      <div ref={elementRef} className="ad">
        This is div element
      </div>
  );
};
export default Ref;