useRef hook in react to manage dom element and state Easy 2025
useRef Hook in React to Manage DOM Elements and State Easily
useRef
is a hook in React that lets you persist values across renders without causing re-renders. It is commonly used to access DOM elements directly or store mutable variables.
🎯 Real-World Example: Focus Input on Button Click
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
);
}
export default FocusInput;
🧠 How it works:
useRef()
creates a reference object with a current
property.
- The
ref
is attached to the input element.
- When the button is clicked, we call
inputRef.current.focus()
to focus the input field.