Lesson 28 of 3093%
(Progress persistence is disabled until Phase 9)
React
Beginner
useRef
Referencing a value that’s not needed for rendering.
useRef is like a “box” that can hold a mutable value.
Unlike useState, changing the current value of a ref does not trigger a re-render.
It is commonly used to hold references to HTML DOM elements.
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
function handleFocus() {
// Directly access the underlying HTML element
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleFocus}>Focus the input</button>
</div>
);
}
Try It Yourself