What is useRef in react and how to use it correctly
useRef is a React hook that allows you to obtain a reference to the underlying DOM object associated with a React component. It is particularly useful when you need to make direct changes to the DOM object without relying on other React primitives.
In most normal components you do not need a ref. Ideally usage of this hook should be avoided as much as possible as it makes the code harder to understand and changes to dom a bit more bug prone. But there might be some valid cases where this is needed. When you make changes to DOM using a ref, it bypasses the virtual DOM of react.
There are many useful libraries such as D3.js which you might want to use but they don't play well with react ecosystem. In such cases it might be sensible to use them to manipulate the DOM directly. It is a valid case but you should always remember that when these libraries make changes to the DOM, those changes will not be accessible to React's virtual DOM.
Some of the scenarios where such usage is normal is when you want to display charts, graphs drawn on an Canvas element.
You can use useRef to store a value that doesn't trigger re-renders when it changes, which is useful for some use cases like persisting data between renders.
References is a common way to manage focus when you want to programmatically control where the keyboard focus should be even after the elment is re-renderd.
You can also provide an initial valye to the useRef hook.
Using react with form elements
Avoid using useRef, but when you must use it, please make sure the use case is valid and there is no native react pattern to achieve what you are trying to achieve.
Please refer to the official documentation here.