useRef

what is useRef() ?

  • Profile picture of Mcs
  • by Mcs July 2, 2025

useRef is a React Hook that provides a way to create a mutable reference to a value or a DOM element that persists across component renders without triggering re-renders.

useRef() is a React Hook that lets you:

  1. Access or reference DOM elements directly
  2. Store mutable values that persist across renders (without causing re-renders)

Syntax

const myRef = useRef(initialValue);

  1. myRef.current stores the value
  2. It does not trigger a re-render when updated

Common Uses of useRef()

1. Accessing a DOM Element

import { useRef } from 'react';

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

 const focusInput = () => {
   inputRef.current.focus(); // Focus the input element
 };

 return (
   <>
     <input ref={inputRef} type="text" />
     <button onClick={focusInput}>Focus Input</button>
   </>
 );
}

2. Storing a Mutable Value Without Re-render

import { useRef, useState, useEffect } from 'react';

function Timer() {
 const [count, setCount] = useState(0);
 const countRef = useRef(0); // store current count without triggering re-render

 useEffect(() => {
   const interval = setInterval(() => {
     countRef.current += 1;
     setCount(countRef.current); // update visible count
   }, 1000);

   return () => clearInterval(interval);
 }, []);

 return <h2>Timer: {count}</h2>;
}

3. Preserving Previous Value

import { useRef, useEffect, useState } from 'react';

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

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

 return (
   <>
     <h2>Now: {count}</h2>
     <h4>Before: {prevCount.current}</h4>
     <button onClick={() => setCount(count + 1)}>+1</button>
   </>
 );
}

Summary

FeatureDescription
useRef()Stores a persistent value across renders
ref.currentAccess the value or DOM node
Doesn’t re-renderUpdating ref.current does not trigger re-render
Common useDOM access, timers, previous value, local counters

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.