JAVASCRIPT
Direct DOM Manipulation and Mutable Values with useRef
Learn to use the `useRef` hook in React for direct access to DOM elements or to persist mutable values across renders without causing re-renders.
import React, { useRef, useEffect } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const counterRef = useRef(0); // For persistent mutable value
useEffect(() => {
// Focus the input element on component mount
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
const handleButtonClick = () => {
counterRef.current = counterRef.current + 1;
alert(`Counter value: ${counterRef.current}. This does not cause a re-render.`);
// If you want to see the updated value in the UI, you'd need useState
};
return (
<div>
<input type="text" ref={inputRef} placeholder="I will focus on load" />
<button onClick={handleButtonClick}>Increment Internal Counter (useRef)</button>
<p>Open console to see component renders. `counterRef` update doesn't trigger re-render.</p>
</div>
);
}
export default FocusInput;
How it works: The `useRef` hook provides a way to access DOM nodes directly or to store a mutable value that doesn't cause a re-render when updated. It returns a mutable `ref` object whose `.current` property is initialized to the passed argument. For DOM access, you attach the ref object to a JSX element's `ref` attribute. For persistent values, you can update `ref.current` without triggering component re-renders.