πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Refs and DOM Access

React Fundamentals🟒 Free Lesson

Advertisement

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.

⭐

Premium Content

Refs and DOM Access

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement