Explain useRef Hook in React

The useRef hook in React is used to create a mutable reference that persists across re-renders of a component. It allows us to access and modify the properties of a DOM element or a value without triggering a re-render.

To use the useRef hook, we first import it from the ‘react’ package:

import React, { useRef } from 'react';

Then, within a functional component, we can create a ref by calling the useRef function:

const myRef = useRef();

We can then attach this ref to a DOM element by using the ref attribute:

<input ref={myRef} type="text" />

Now, we can access and modify the properties of the input element using the current property of the ref:

myRef.current.value = 'Hello, World!';

The current property holds the current value of the ref, and any changes made to it will not cause a re-render of the component.

The useRef hook is also useful for storing values that need to persist across re-renders, similar to instance variables in class components. For example, we can store a counter value that persists across re-renders:

const counterRef = useRef(0);
counterRef.current++; // Increment the counter value

In this case, the current property of the counterRef will hold the current value of the counter, and we can modify it without triggering a re-render.

Overall, the useRef hook in React provides a way to create mutable references that persist across re-renders, allowing us to access and modify DOM elements or values without causing unnecessary re-renders.