React useRef Hook

📘 React.js 👁 37 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

The useRef hook provides a way to persist values across renders without causing a re-render. It is commonly used to access DOM elements or store mutable values.


What is useRef?

  • Returns a mutable object with a .current property

  • Value persists between renders

  • Updating .current does not trigger a re-render

import { useRef } from "react"; const ref = useRef(initialValue);

Accessing DOM Elements

One of the most common use cases.

function FocusInput() { const inputRef = useRef(null); function focusInput() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={focusInput}>Focus</button> </> ); }

Storing Mutable Values

function Timer() { const countRef = useRef(0); function increment() { countRef.current += 1; console.log(countRef.current); } return <button onClick={increment}>Increment</button>; }
  • Value changes

  • Component does not re-render


useRef vs useState

useRefuseState
No re-renderTriggers re-render
MutableImmutable updates
DOM accessUI data
Persistent storageReactive state

Preserving Previous Values

function PreviousValue({ value }) { const prevValue = useRef(); useEffect(() => { prevValue.current = value; }, [value]); return <p>Previous: {prevValue.current}</p>; }

useRef with Timers

function Timer() { const timerRef = useRef(null); useEffect(() => { timerRef.current = setInterval(() => { console.log("Running"); }, 1000); return () => clearInterval(timerRef.current); }, []); }

Forwarding Refs (Brief)

const Input = React.forwardRef((props, ref) => ( <input ref={ref} /> ));

Allows parent components to access child DOM nodes.


Common Mistakes

❌ Using useRef instead of state for UI updates
❌ Expecting re-render on ref change
❌ Overusing refs


Best Practices

  • Use refs for DOM access

  • Use state for UI logic

  • Keep ref usage minimal

  • Avoid mutating UI-related data


Key Points

  • useRef stores mutable values

  • Does not cause re-render

  • Ideal for DOM and timers

  • Persists across renders


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes