Use of ref

PUBLISHED: MAY 2, 2026•1 MIN READ

What is ref in React?A ref is a way to directly access a DOM element or store a mutable value that does NOT cause re-render when it changes.In modern React, we

Divya Sachan
Divya SachanAuthor
slowbro
#080
slowbro

What is ref in React?

A ref is a way to directly access a DOM element or store a mutable value that does NOT cause re-render when it changes.

In modern React, we use useRef.

šŸ”¹ Basic Syntax

javascript
import { useRef } from "react";

const myRef = useRef(null);
  • myRef is an object
  • myRef.current holds the value
  • Updating .current does not re-render

šŸ”¹ 1. Accessing DOM Elements (Most Common Use)

Example: Focus Input

javascript
import { useRef } from "react";

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

  return (
    <>
      
      
    
  );
}

āœ… Direct DOM access
āŒ No state needed

šŸ”¹ 2. Persist Value Without Re-render

Example: Render Counter

javascript
import { useRef, useState } from "react";

function App() {
  const renderCount = useRef(0);
  const [count, setCount] = useState(0);

  renderCount.current++;

  return (
    <>
      

Count: {count}

Renders: {renderCount.current}

); }

āœ” renderCount updates
āœ” UI updates only when state changes

šŸ”¹ 3. Store Previous State Value

javascript
import { useRef, useEffect, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const prevCount = useRef(null);

  useEffect(() => {
    prevCount.current = count;
  }, [count]);

  return (
    <>
      

Current: {count}

Previous: {prevCount.current}

); }

šŸ”¹ 4. Store Timers / Intervals (Interview Favorite)

javascript
import { useRef, useState } from "react";

function Stopwatch() {
  const timerRef = useRef(null);
  const [time, setTime] = useState(0);

  const start = () => {
    if (!timerRef.current) {
      timerRef.current = setInterval(() => {
        setTime(t => t + 1);
      }, 1000);
    }
  };

  const stop = () => {
    clearInterval(timerRef.current);
    timerRef.current = null;
  };

  return (
    <>
      

Time: {time}s

); }

āœ” Interval persists across renders
āœ” No unwanted re-renders

šŸ”¹ 5. useState vs useRef (Core Difference)

FeatureuseStateuseRef
Triggers re-renderāœ…āŒ
DOM accessāŒāœ…
Store mutable valueāŒāœ…
UI updateāœ…āŒ

šŸ”¹ When NOT to Use ref

āŒ For displaying data in UI
āŒ For main application state
āŒ As replacement for state

Rule:
UI change → useState
Logic / DOM / memory → useRef

šŸ”¹ One-Line Interview Answer

ā€œuseRef lets us access DOM elements and store mutable values that persist across renders without causing re-render.ā€