DEV Community

Cover image for useRef in React
Amogh Nandodkar
Amogh Nandodkar

Posted on

useRef in React

Getting started with useRef

To get started with useRef hook we first need to import it from React as :

import { useRef } from 'react';
Enter fullscreen mode Exit fullscreen mode

The hook only takes a single initial value and returns a ref.

const initialRef = useRef(null);
Enter fullscreen mode Exit fullscreen mode

In the above example we created a ref named initialRef and it is set to a default value of null. useRef assigns the ref to an object having a current property,

{ current : null }
Enter fullscreen mode Exit fullscreen mode

Looking at the above example you might be thinking why don't we use the useState instead of useRef hook. The main difference between the useState and useRef is that the later persists between renders and doesn't cause the component to re-render each time its value changes.

Using useRef hook

Until now we have understood that the main use of ref is for storing value between renders.

The most common use of refs is to reference the DOM elements, in fact every DOM element has a ref property which can be used for setting ref to the element.


function InputWithButton() {
  const initialRef = createRef(); 
  const handleClick = () => {
    initialRef.current.focus();
  };
  return (
    <div>
      <input ref={initialRef} type="text" />
      <button onClick={handleClick}>Focus</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In the above example, we have used the ref property of the input ref in order to set the current property. When we click the button it calls the handleClick which uses the current value to set focus on the input element. Thus being able to access any DOM element by using the useRef hook is extremely useful for managing attributes which cannot be directly controlled in React.

Conclusion

useRef hook in React is extremely useful for storing data between renders without causing the element to re-render each time. It can also be used for accessing DOM elements.

Top comments (0)