React Hooks
April 2, 20252 min read...
React HooksApril 2, 20252 min read

useRef Mastery: DOM Refs, Instance Variables, and forwardRef

Complete guide to useRef and refs in React – accessing DOM elements, storing mutable values without re-renders, forwarding refs, and building imperative component APIs.

useRef Mastery: DOM Refs, Instance Variables, and forwardRef

Two Main Uses of useRef

1. DOM refs: Directly access HTML elements. 2. Instance variables: Store mutable values that persist across renders without causing re-renders.

DOM Ref Example

function InputFocus() {
  const inputRef = useRef(null);

useEffect(() => { inputRef.current.focus(); }, []);

return <input ref={inputRef} />; }

Instance Variable (no re-render)

function Timer() {
const intervalRef = useRef(null);

const startTimer = () => { intervalRef.current = setInterval(() => {}, 1000); };

const stopTimer = () => { clearInterval(intervalRef.current); };

return <button onClick={stopTimer}>Stop</button>; }

forwardRef + useImperativeHandle

const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();

useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus(), scrollToTop: () => inputRef.current.scrollTop = 0 }));

return <input ref={inputRef} />; });

function Parent() { const ref = useRef(); return <><FancyInput ref={ref} /><button onClick={() => ref.current.focus()}>Focus</button></>; }

Performance Tips

  • Reading/writing refs doesn’t trigger re-renders – use for performance-critical mutable data
  • Avoid setting refs during render – use effect or callbacks

Common Mistakes

  • Using refs for state that should trigger UI updates
  • Expecting ref changes to cause re-renders
  • Not using forwardRef when passing ref to custom component

Interview Q&A

Q: Difference between useRef and createRef? useRef is for functional components (persists across renders). createRef is for class components.
Q: Can you use ref on a custom component? Only if that component uses forwardRef.

Conclusion

useRef is essential for imperative DOM operations and mutable storage. Master forwardRef and useImperativeHandle for reusable component APIs.

Comments

Join the conversation — sign in to leave a comment.