React DOM Secrets: Unleash the Power of useRef() with Examples
Here’s a detailed explanation of the useRef
hook in React, with examples:
Purpose:
- Creates a mutable reference object that persists throughout the component’s lifecycle.
- Used to access DOM elements or store mutable values directly without triggering re-renders.
Key Points:
- Returns a mutable ref object:
const myRef = useRef(initialValue);
- Current value accessible through
.current
property:myRef.current
- Doesn’t trigger re-renders when updated: Unlike state, changing a ref’s value doesn’t cause the component to re-render.
- Persists across renders: The ref object remains the same throughout the component’s lifecycle.
Common Use Cases:
- Accessing DOM Elements:
Javascript
import { useRef } from 'react';
function MyComponent() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus(); // Focus the input element
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}
- Storing Mutable Values:
Javascript
function Counter() {
const countRef = useRef(0);
const increment = () => {
countRef.current++; // Update the count without re-render
};
return (
<div>
Count: {countRef.current}
<button onClick={increment}>Increment</button>
</div>
);
}
- Measuring Dimensions:
Javascript
function ImageWithDimensions() {
const imageRef = useRef(null);
useEffect(() => {
if (imageRef.current) {
console.log(imageRef.current.offsetWidth, imageRef.current.offsetHeight);
}
}, []);
return <img ref={imageRef} src="..." />;
}
Remember:
- Use
useRef
for direct access and mutations, not for state management. - For managing data that triggers UI updates, use the
useState
hook.