Basic Syntax

Stores a mutable reference to a DOM element or value without causing re-render.

import { useRef } from 'react';
const ref = useRef<HTMLElement>(null);

Example: DOM Element Access

import { useRef } from 'react';

function TextInput() {
  const inputRef = useRef<HTMLInputElement>(null);

  const focusInput = (): void => {
    inputRef.current?.focus();
  };

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>Focus</button>
    </>
  );
}

Common Use Cases

Mutable Value Example

const intervalRef = useRef<number | null>(null);

useEffect(() => {
  intervalRef.current = window.setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => {
    if (intervalRef.current) clearInterval(intervalRef.current);
  };
}, []);

Previous Value Example

  const [count, setCount] = useState(0);
  const prevCountRef = useRef<number>();

  useEffect(() => {
    prevCountRef.current = count;
  }, [count]);

  const prev = prevCountRef.current;