How to Use the useRef Hook in React
A step-by-step guide on how to use useRef to access DOM elements directly and persist mutable values across renders without causing re-renders.
Understand What useRef Returns
useRef returns a plain JavaScript object with a single property called current. This object persists for the full lifetime of the component. Unlike state, updating the current property does not trigger a re-render. It is a mutable container that survives across renders.
Import and Initialize useRef
Import useRef from react and call it inside your component. Pass an initial value as the argument, which becomes the starting value of the current property. For DOM access, pass null as the initial value because the DOM element does not exist yet during initialization.
Attach the Ref to a DOM Element
To get a direct reference to a DOM element, pass the ref object to the ref attribute of a JSX element. Write ref={myRef} on the element. After the component mounts, React sets myRef.current to the actual DOM node, giving you full access to its properties and methods.
Access and Manipulate the DOM Element
Once the component has mounted, read and call DOM properties through myRef.current. For example, call myRef.current.focus() to programmatically focus an input field, or read myRef.current.scrollHeight to measure an element's dimensions. Do this inside a useEffect to ensure the DOM is ready.
Store Mutable Values Without Re-renders
useRef is also useful for storing values that need to persist across renders but should not trigger a re-render when they change. Common examples include storing a previous state value, tracking how many times a component has rendered, or holding a timer ID from setInterval so you can clear it later.
Store the Previous Value of State
To track the previous value of a state variable, create a ref and update it inside a useEffect. The effect runs after the render, so inside the effect you set ref.current to the current state value. On the next render, ref.current still holds the previous value before the effect updates it again.
Understand the Difference Between useRef and useState
useState causes a re-render when its value changes and the value is read inside JSX. useRef does not cause a re-render when current changes. Use useState for values that should update the UI. Use useRef for values that the component needs to remember but that should not affect what is displayed.
Avoid Overusing useRef for DOM Access
Only use useRef for DOM access when React's declarative model cannot achieve what you need, such as focusing an input, playing a video, or measuring element dimensions. For most UI changes, managing state and letting React update the DOM is the correct approach.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

