Skillversitas

Refs & DOM

Why Refs?

Refs access the DOM directly from a React component. They are ideal for auto-focus, measuring sizes, and integrating external libraries.

useRef for the DOM

import { useRef, useEffect } from 'react';

function AutoFocusInput() {
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current.focus(); }, []);
  return <input ref={inputRef} placeholder="Auto focus" />;
}

Controlled vs Uncontrolled

Aspect Controlled Uncontrolled
Value Managed by React state Managed by the DOM
Update onChange + setState Read via ref
Example <input value={x} onChange={...} /> ref.current.value

Ref Forwarding

const FancyInput = React.forwardRef((props, ref) => {
  return <input ref={ref} className="fancy" {...props} />;
});

function Parent() {
  const ref = useRef(null);
  return (
    <>
      <FancyInput ref={ref} />
      <button onClick={() => ref.current.focus()}>Focus</button>
    </>
  );
}

When to Use Refs

  • Auto-focus on mount
  • Storing timer IDs
  • Measuring an element's size/position
  • Integrating drag-and-drop, charts

Measuring an Element's Size

function MeasureBox() {
  const ref = useRef(null);
  const [size, setSize] = useState({ w: 0, h: 0 });
  useEffect(() => {
    const { width, height } = ref.current.getBoundingClientRect();
    setSize({ w: Math.round(width), h: Math.round(height) });
  }, []);
  return <div ref={ref} style={{ padding: 20 }}><p>{size.w}x{size.h}</p></div>;
}

Refs are imperative — use state for data that triggers a render. Next chapter: Error Boundaries.