Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
useRef is a hook in React that allows storing references to DOM elements or values that don't cause component re-render when changed. This can be useful for accessing DOM elements or storing values between renders.
References to DOM elements. useRef can be used to get direct access to DOM elements, for example, to focus on input field or measure element sizes.
Storing values between renders. useRef stores value that doesn't cause component re-render when changed. This is useful when you need to store data that shouldn't be part of component state but should persist between renders.
const myRef = useRef(initialValue);
initialValue — initial reference value. It can be null or any other value you need to store.
myRef.current — object that stores current value. For DOM element references, myRef.current will reference the element itself.
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // Focus on input field
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus on input</button>
</div>
);
}
In this example:
inputRef is created using useRef and passed to input field's ref attribute.import { useRef } from "react";
function Timer() {
const countRef = useRef(0);
const increment = () => {
countRef.current += 1;
console.log(countRef.current); // Prints number of updates
};
return (
<div>
<button onClick={increment}>Increment</button>
</div>
);
}
In this example:
countRef is used to store counter value between renders.Using useRef:
useRef allows storing data or element references between renders without causing unnecessary re-renders, making it ideal tool for DOM work and storing state that doesn't affect rendering.