Refs and DOM Access
useRef, forwardRef, callback refs, and managing focus, scroll, and media.
Overview
Refs provide direct access to DOM elements and persist values across renders.
Key Concepts
- useRef — Creates a mutable ref object
- forwardRef — Passes refs to child components
- Callback Refs — Custom logic when ref is attached/detached
- useImperativeHandle — Customizes ref value exposed to parent
- Common Uses — Focus management, scroll, media playback, animations
Code Examples
import { useRef, forwardRef, useImperativeHandle } from 'react';
const TextInput = forwardRef(function TextInput(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inputRef.current?.focus(),
clear: () => { inputRef.current.value = ''; }
}));
return <input ref={inputRef} {...props} />;
});
function Form() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<form onSubmit={e => e.preventDefault()}>
<TextInput ref={inputRef} placeholder="Auto-focused input" />
<button type="button" onClick={() => inputRef.current?.clear()}>
Clear
</button>
</form>
);
}
Practice
Build an auto-complete component with keyboard navigation using refs.