In React.js, theuseRef
hook is used to create mutable object properties that persist across renders without causing re-renders when the value changes. It's often used to get a reference to a DOM element or to persist values between renders without triggering a re-render.
Here's a simple example of using useRef
:
import React, { useRef, useEffect } from 'react';
function ExampleComponent() {
// Create a ref object
const myRef = useRef(null);
// useEffect to focus on the input element when the component mounts
useEffect(() => {
myRef.current.focus();
}, []);
return (
<div>
{/* Attach the ref to the input element */}
<input ref={myRef} type="text" />
</div>
);
}
export default ExampleComponent;
In this example:
We import
useRef
from the React library.We create a ref object using
const myRef = useRef(null);
.We attach this ref to an input element using the
ref
attribute:<input ref={myRef} type="text" />
.We use the
useEffect
hook to focus on the input element when the component mounts. TheuseEffect
hook runs after the initial render.
Here's a breakdown:
useRef(null)
creates aref
object with an initial value ofnull
.The
ref
is attached to theinput
element, makingmyRef.current
refer to theinput
DOM node.In the
useEffect
hook, when the component mounts ([]
as the dependency array), it callsmyRef.current.focus()
, focusing on the input element.
Conclusion:
The key point here is that changes to the ref
object (myRef.current
) don't cause the component to re-render. This makes useRef
useful for holding mutable values that persist across renders without triggering unnecessary re-renders.