React useRef Hook

React useRef Hook


The React useRef Hook allows you to access the underlying DOM element of a component. It is a way to store a reference to a DOM node or a component instance, so you can directly interact with it.

To use the useRef Hook, you need to import it from the React library and call it inside a functional component. The Hook returns an object with a current property, which you can use to store a reference to a DOM node or a component instance.

Here's an example of how to use useRef to store a reference to a DOM node:

In this example, we are using the useRef Hook to store a reference to the input element, and then we are using that reference to call the focus method on the input element when the button is clicked.

Another example you can use useRef for is to store the state of a component, instead of using state, you can use ref to store the state and mutate it directly

In this example, we are using the useRef Hook to store the state of the component and mutating it directly, instead of using the state and setState.

It's important to note that the useRef Hook returns the same object on every render, so it's not a way to store a changing value. If you need to store a changing value, you should use the useState Hook instead.