DEV Community

mohandass
mohandass

Posted on

useRef in React

  • useRef is a build-in React Hook that returns a mutable object whose.current property persists across re-renders without triggering a component re-render when modified.It acts an "escape hatch" to store the data outside of React's standard visual render cycle.

Syntax :

import { useRef } from "react";

const ref = useRef(initialValue);

{
  current: initialValue
}
Enter fullscreen mode Exit fullscreen mode
  • This returns a plain JavaScript object structured exactly like { current: initialValue }.

  • Manipulating the DOM you can directly link a ref object to an HTML node using the ref attribute. This is commonly used for managing focus, text selection, or triggering media play/pause mechanics.

  • Storing Mutable Variables It lets you hold variables that shouldn't reset when components re-render.

  • Caching Previous Props/State It allows you to preserve the historical value of state or props from the prior render cycle to run delta comparisons.

Rule

  • Do not read or write ref.current during rendering. Doing so makes your component impure because render operations must stay deterministic.
  • Only interact with refs inside event handlers or useEffect. You should update or evaluate refs within events or post-render side effects.

Top comments (0)