React JS useRef Hook
The useRef hook is the new addition in React 16.8. Before proceeding to this article there is a prerequisite to know about the ref in react.
The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.
const refContainer = useRef(initialValue);
The useRef returns a mutable ref object. This object has a property called .current. The value is persisted in the refContainer.current property. These values are accessed from the current property of the returned object. The .current property could be initialised to the passed argument initialValue e.g. useRef(initialValue). The object can persist a value for a full lifetime of the component.
Example: How to access the DOM using useRef hook.
Output: In this example, we have a button called ACTION, whenever we click on the button the onClickHandler is getting triggered and it’s focusing the textarea with help of useRef hook. The focusPoint is the useRef object which is initialised to null and the value is changing to onClick event. Let’s see the output of the above code.