React Native theorytheory 0/50 · 0%
Hooks · easy

17. useRef and mutable values

Values that persist without triggering renders.

`useRef` holds a mutable `.current` value that survives re-renders without causing one when changed — used for timers, previous values, or references to native components.

import { useRef, useEffect } from "react";

function usePrevious<T>(value: T): T | undefined {
  const ref = useRef<T>();
  useEffect(() => { ref.current = value; }, [value]);
  return ref.current;
}

Refs are also how you imperatively call methods on native components, e.g. `inputRef.current?.focus()` on a `TextInput` after a modal opens.

Check your understanding

  1. 1. Does updating ref.current trigger a re-render?

  2. 2. What is a common use of refs with native components?

  3. 3. What does useRef return?