#javascript#reactjs#beginers
To get started with useRef hook we first need to import it from React as:
import { useRef } from 'react';
The hook only takes a single initial value and returns a ref.
const initialRef = useRef(null);
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 }
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.
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.
import { useRef } from "react";
function InputWithButton() {
const initialRef = useRef();
const handleClick = () => {
initialRef.current.focus();
};
return (
<div>
<input ref={initialRef} type="text" />
<button onClick={handleClick} >Focus</button>
</div>
);
}
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.
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.