In React, the useRef
hook is used to create a mutable object that persists across renders without causing the component to re-render when the object is changed. This can be useful for accessing and interacting with the DOM directly, managing focus, or persisting values across renders without triggering a re-render.
Here's a basic example of how to use the useRef
hook:
jsximport React, { useRef, useEffect } from 'react';
function MyComponent() {
// Create a ref object
const myRef = useRef(null);
useEffect(() => {
// Access the current property to get the DOM element
if (myRef.current) {
// Do something with the DOM element
myRef.current.focus();
}
}, []);
return (
<div>
{/* Attach the ref to a JSX element */}
<input ref={myRef} type="text" />
</div>
);
}
export default MyComponent;
In this example:
useRef(null)
creates a ref object with an initial value of null
.myRef.current
provides access to the DOM element. In this case, it's used within the useEffect
hook to focus on an input element when the component mounts ([]
dependency ensures that the effect runs only once after the initial render).ref
attribute is used to attach the ref to a JSX element (<input>
in this case).Here are a few common use cases for useRef
:
jsximport React, { useRef, useEffect } from 'react';
function MyComponent() {
const myRef = useRef(null);
useEffect(() => {
if (myRef.current) {
// Access or modify the DOM element
myRef.current.style.backgroundColor = 'lightblue';
}
}, []);
return (
<div ref={myRef}>
{/* ... */}
</div>
);
}
export default MyComponent;
jsximport React, { useRef, useState } from 'react';
function MyComponent() {
const inputValueRef = useRef('');
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
// Update the ref without causing a re-render
inputValueRef.current = event.target.value;
// Update state to trigger a re-render
setInputValue(event.target.value);
};
return (
<div>
<input value={inputValue} onChange={handleChange} />
<p>Input value (using ref): {inputValueRef.current}</p>
</div>
);
}
export default MyComponent;
In this example, the ref is used to store the input value without causing a re-render, while the state is used for rendering purposes.