How to use the useRef Hook in React?

The useRef Hook in React allows you to create a mutable object that persists for the entire lifetime of the component. Here's how you can use the useRef Hook in React:

  1. Import the useRef Hook at the top of your functional component:
import React, { useRef } from 'react';
  1. Initialize a ref object using the useRef Hook:
const myRef = useRef(initialValue);

You can pass an optional parameter to useRef to set the initial value of the ref object. If you don't need an initial value, you can omit this parameter.

  1. Attach the ref object to a JSX element using the ref attribute:
return <div ref={myRef}>Hello, world!</div>;
  1. Access the current value of the ref object using .current:
console.log(myRef.current);

Keep in mind that when you update the value of the ref object, React will not re-render the component. This makes useRef ideal for storing mutable values that do not need to trigger a re-render.

Overall, the useRef Hook is useful for accessing DOM elements directly, managing focus, or storing mutable values that persist between renders.