JAVASCRIPT
Interact with DOM or Mutable Values using useRef Hook
Learn to directly access DOM elements or persist mutable values across renders without causing re-renders using the React useRef hook, ideal for interactions.
import React, { useRef, useEffect } from 'react';
function TextInputWithFocusButton() {
const inputRef = useRef(null);
const counterRef = useRef(0); // For mutable values that don't trigger re-render
useEffect(() => {
// Accessing the DOM element directly
if (inputRef.current) {
inputRef.current.focus();
}
}, []); // Run once on mount
const handleButtonClick = () => {
if (inputRef.current) {
inputRef.current.focus();
inputRef.current.value = 'Focused!';
}
counterRef.current += 1;
console.log('Counter value (no re-render):', counterRef.current);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleButtonClick}>Focus Input & Increment Counter</button>
<p>Check console for counter value. It changes without component re-rendering.</p>
</div>
);
}
export default TextInputWithFocusButton;
How it works: The useRef hook provides a way to access the DOM node directly or to store a mutable value that persists across renders but doesn't cause a re-render when updated. It returns a mutable 'ref' object whose '.current' property is initialized to the passed argument. The returned ref object will persist for the full lifetime of the component. It's commonly used for managing focus, text selection, media playback, or integrating with third-party DOM libraries.