React từ cơ bản đến nâng cao
Trang chủ / Module 6
📌 Module 6 / 22 · 3 ngày 📅 Tuần 3 ●●○○ Trung bình

useRef, thao tác DOM và ref như một prop

useRef để giữ giá trị không gây render và để truy cập DOM, ref là prop thường trong React 19, ref callback có cleanup, useImperativeHandle và khi nào không nên dùng ref.

useRefDOMref callbackuseImperativeHandle
📌 Vì sao module này quan trọng

Ref là "lối thoát" khỏi luồng dữ liệu của React. Dùng đúng thì giải quyết được focus, scroll, đo kích thước, tích hợp thư viện bên ngoài. Dùng sai (đọc/ghi ref khi render, dùng ref thay state) thì giao diện không cập nhật và rất khó debug.

🎯 Mục tiêu học tập

  • Phân biệt ref và state: cái nào gây render lại
  • Truy cập DOM để focus, scroll, đo kích thước
  • Truyền ref xuống component con (React 19: ref là prop, không cần forwardRef)
  • Dùng ref callback và cleanup của nó cho danh sách động
  • Giới hạn API mở ra cho cha bằng useImperativeHandle

Ref là cái hộp không gây render

function Stopwatch() {
  const [now, setNow] = useState(null);
  const [start, setStart] = useState(null);
  const intervalRef = useRef(null);       // { current: null }, giữ nguyên qua mọi lần render

  function handleStart() {
    setStart(Date.now()); setNow(Date.now());
    clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => setNow(Date.now()), 10);
  }
  const handleStop = () => clearInterval(intervalRef.current);
  const seconds = start && now ? (now - start) / 1000 : 0;
  return (<><h1>{seconds.toFixed(2)}</h1><button onClick={handleStart}>Bắt đầu</button><button onClick={handleStop}>Dừng</button></>);
}
stateref
Đổi giá trị có render lại?CóKhông
Đọc khi renderĐượcKhông nên (trừ khởi tạo lười)
Dùng choThứ hiển thị trên màn hìnhTimer id, DOM node, giá trị trước, instance thư viện

Truy cập DOM

function SearchBox() {
  const inputRef = useRef(null);
  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
      <button onClick={() => inputRef.current.scrollIntoView({ behavior: 'smooth' })}>Cuộn tới</button>
    </>
  );
}

ref.current được gán sau khi commit, nên chỉ đọc trong event handler hoặc effect, không đọc khi render.

React 19: ref là prop thường

// React 19
function TextInput({ ref, ...props }) {
  return <input ref={ref} {...props} />;
}

// Trước React 19 phải dùng forwardRef (vẫn chạy, sẽ bị khai tử dần)
const TextInputOld = forwardRef(function TextInputOld(props, ref) {
  return <input ref={ref} {...props} />;
});

Ref callback và cleanup

Thay vì object, có thể truyền hàm vào ref. React gọi hàm với DOM node khi gắn. Từ React 19, hàm này có thể trả về cleanup — rất tiện cho danh sách động hoặc gắn observer.

function Gallery({ images }) {
  const nodes = useRef(new Map());
  const scrollTo = id => nodes.current.get(id)?.scrollIntoView({ behavior: 'smooth', inline: 'center' });

  return (
    <ul>
      {images.map(img => (
        <li key={img.id} ref={node => {
          nodes.current.set(img.id, node);
          return () => nodes.current.delete(img.id);   // cleanup khi phần tử bị gỡ
        }}>
          <img src={img.src} alt={img.alt} />
        </li>
      ))}
    </ul>
  );
}

useImperativeHandle: chỉ mở ra những gì cần

function VideoPlayer({ ref, src }) {
  const videoRef = useRef(null);
  useImperativeHandle(ref, () => ({
    play: () => videoRef.current.play(),
    pause: () => videoRef.current.pause(),
  }), []);
  return <video ref={videoRef} src={src} />;
}

// Cha chỉ gọi được play/pause, không chạm được toàn bộ thẻ video
const player = useRef(null);
<VideoPlayer ref={player} src="/intro.mp4" />
<button onClick={() => player.current.play()}>Phát</button>

Đừng dùng ref để làm thứ props làm được (ví dụ modal.open()); ưu tiên <Modal isOpen={...} />. Ref dành cho hành vi mệnh lệnh thật sự: focus, scroll, play, đo đạc.

Tích hợp thư viện không phải React

function MapView({ center }) {
  const containerRef = useRef(null);
  const mapRef = useRef(null);

  useEffect(() => {
    mapRef.current = new maplibregl.Map({ container: containerRef.current, center, zoom: 12 });
    return () => { mapRef.current.remove(); mapRef.current = null; };
  }, []);                                   // tạo 1 lần

  useEffect(() => { mapRef.current?.setCenter(center); }, [center]);  // đồng bộ prop -> thư viện

  return <div ref={containerRef} style={{ height: 400 }} />;
}

🚩 Sai lầm hay gặp

  • Dùng ref cho dữ liệu hiển thị rồi thắc mắc vì sao màn hình không cập nhật.
  • Đọc ref.current khi render (giá trị có thể là null hoặc cũ).
  • Tự sửa DOM do React quản lý (xoá node bằng remove()) — React mất đồng bộ và báo lỗi.

🏋️ Bài tập thực hành

Ô OTP 6 số

6 ô input, gõ 1 số tự nhảy sang ô sau, Backspace ở ô trống quay về ô trước, dán chuỗi 6 số tự điền hết. Dùng ref callback cho danh sách ô. Viết component OtpInput nhận ref để cha gọi focus() và clear() qua useImperativeHandle.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi biết khi nào dùng ref, khi nào dùng state
  • Tôi truyền được ref xuống component con theo cách React 19
  • Tôi viết được ref callback có cleanup
  • Tôi tích hợp được một thư viện JS thuần vào component có cleanup đúng