Table of contents
Refs let a component hold some information that isn’t used for rendering, like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an “escape hatch” from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
useRef:
declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node.
The useRef hook in React is primarily used to create and hold references to DOM elements or to persist values across renders without causing re-renders. It provides a way to interact with the DOM and access elements directly, similar to using the ref attribute in class components.
initial value usually null
Triggering Re-renders: While useRef is typically used for accessing DOM elements and storing mutable values without re-renders, it does not trigger re-renders when its value changes. If you want to trigger a re-render when a value changes, you should use useState or useReducer instead.
useRef Example
import React, { useRef } from "react";
function UseRefEg() {
const inputRef = useRef(null);
const getValue = () => {
console.log(inputRef.current.value);
};
const giveFocus = () => {
inputRef.current.focus();
};
const setReset = () => {
inputRef.current.value = "";
};
return (
<div>
UseRefEg
<h1>Dev</h1>
<input type="text" placeholder="Ex.." ref={inputRef} />
<button onClick={getValue}>Get Name</button>
<button onClick={giveFocus}>Bring Focus</button>
<button onClick={setReset}>Reset Value without rerendering</button>
</div>
);
}
export default UseRefEg;
useImperativeHandle
lets you customize the ref exposed by your component. This is rarely used.
useImperativeHandle
is a React Hook that allows you to customize the ref that is exposed by your component when it is used withReact.forwardRef
. This hook is useful in specific scenarios where you want to control what properties or methods are accessible through the ref of a child component.