useRef Hook

  • This lesson introduces the useRef Hook and explains how to use it for DOM access and persisting values across renders.

  • Accessing DOM Elements

    useRef allows direct access to DOM elements.

    Example:

const inputRef = useRef();

<input ref={inputRef} />

inputRef.current.focus();
  • Common use cases:

    • Focus input

    • Scroll elements

    • Access media elements

    Persisting Values Without Re-render

    Unlike state, updating useRef does not cause re-render.

    Example:

const countRef = useRef(0);
countRef.current += 1;
  • Useful for:

    • Timers

    • Previous values

    • Counters