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:
useRef
Hook at the top of your functional component:import React, { useRef } from 'react';
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.
ref
attribute:return <div ref={myRef}>Hello, world!</div>;
.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.