React ยท Chapter 14 of 42
useRef Hook
`useRef` returns a mutable object with a `.current` property that persists across renders without causing re-renders when changed. It's commonly used to access DOM nodes directly.
Unlike state, updating a ref does not trigger a re-render, making it ideal for storing values that don't affect the UI.
Accessing DOM nodes
Attach a ref to a JSX element via `ref={myRef}`, then access the actual DOM node with `myRef.current`, e.g. to focus an input.
Storing mutable values
useRef can also hold any mutable value (like a timer ID or previous value) that persists between renders without re-rendering.
Example 1 (jsx)
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus
</button>
</>
);
}Output
(clicking Focus focuses the input)inputRef.current points to the real DOM <input> element.
Key points
- useRef returns a mutable object with a .current property.
- Updating a ref does not trigger a re-render.
- Commonly used to access DOM elements directly.
- Can store any persistent mutable value across renders.
๐ก Note: Don't use refs for values that should drive the UI โ use state for that instead.
