CodePark/ questions / Refs
START PRACTICINGPRACTICE
Frontend question · React › Refs

What is useRef used for, and how does it differ from state?

useRef gives you a box that keeps a value between renders without causing re-renders. useRef(initial) returns an object { current: initial }. It is the same object on every render.

It has two main uses:

  • Accessing DOM nodes. Pass the ref to an element with ref={inputRef}. React sets inputRef.current to the DOM node during the commit, the step where React applies changes to the page. Then you can call focus(), measure the size or scroll.
  • Storing a mutable value that is not used for rendering, like a timer ID or the previous value of something.

The key difference from state: changing ref.current does not trigger a re-render. The change is also visible immediately, not on the next render.

Do not read or write ref.current during render. The one exception is lazy initialisation, which means setting it once when it is still empty. Reading or writing refs during render makes the component impure. Use refs in event handlers and effects.

  • useRef returns a stable { current } object that stays the same across renders.
  • Refs give you access to DOM nodes through the ref attribute.
  • Refs store mutable values like timer IDs.
  • Changing current does not trigger a re-render.
  • Avoid reading or writing refs during render.