🎊How To Use Refs In React With Hooks✨

Hi, I’m Richa — a Senior Frontend Engineer with 5+ years of experience building scalable, production-grade web interfaces for enterprise and consumer applications. I work primarily with React, TypeScript, and modern frontend architectures, focusing on component systems, performance, and maintainability. Most of my experience comes from building real-world products in regulated domains like banking and insurance, where clarity, reliability, and long-term ownership matter more than quick demos. Through this blog, I write about frontend engineering fundamentals, scalable UI design, problem-solving, and the lessons I’ve learned working on large codebases. My goal is to share practical insights — not shortcuts — for developers who want to grow strong engineering foundations. I also mentor early-career developers and strongly believe that curiosity, asking the right questions, and understanding why something works are more important than memorizing tools. If you’re serious about improving as an engineer, you’re in the right place.
Hello React Developers!! 👨💻👩💻 Today we are going to learn about useRef
🎯 Introduction
The useRef hook is the new addition in React 16.8.useRef is short for reference and is a hook which allows you to persist values between renders.

As a reminder, it’s crucial to follow the rules of Hooks when using any Hook, not just useState or useRef:

Hooks should only be called from the top level of your React function
Hooks must not be called from nested code (e.g., loops, conditions)
Hooks may also be called at the top level from custom Hooks
🔑Key Points:-
The
useRefHook allows you to persist values between renders.It can be used to store a mutable value that does not cause a re-render when updated.
It can be used to access a DOM element directly.
🎯useRef
In order to work with refs in React you need to first initialize a ref which is what the useRef hook is for.
This hook is very straightforward, and takes an initial value as the only argument.
📢Syntax:
const reference = useRef("initial value")
In the above example we have created a ref called reference and set its default value to initial value. This means that reference is now equal to an object that looks like this.
{
current: 'initial value'
}
This returns an object which has a key called current, initialized with this initial value.
🎯How To Use Refs
A very common use case for using useRef is for when, suppose you click on a button, and then on its click you want an input to come into focus.
const inputToFocus = useRef(null);
Then on its click you want an input to come into focus. To do this, we would need to access the DOM element of input and then call its function focus() to focus the input.
const clickHandler = () => {
inputToFocus.current.focus();
};
This is easy to do in JavaScript by just selecting the input using querySelector or by id/class and then calling its focus() function, but React does not have a simple way built in to do it. so this can be achieved using useRef.
📍Let see the example
import React, { useRef } from "react";
const Useref = () => {
const inputToFocus = useRef(null);
const clickHandler = () => {
inputToFocus.current.focus();
};
return (
<div>
<input ref={inputToFocus} type="text" placeholder="Enter somethings" />
<button onClick={clickHandler}>Focus on Input</button>
</div>
);
};
export default Useref;
Output:-

🎯 Using Refs Beyond The DOM
While most use cases for refs lie with referencing DOM elements, refs can also be used for any form of storage that is persisted across component renders. A very common use case for this would be storing the previous value of a state variable.
The above code will update the previousName ref every time the name changes so that it always has the previous value of the name variable stored in it. *
📍Let see the example
Use
useRefto keep track of previous state valuesThis time we use a combination of
useState,useEffect, anduseRefto keep track of the previous state.In the useEffect, we are updating the
useRefcurrent value each time thenameis updated by entering text into the input field.
import React, { useEffect, useRef, useState } from "react";
const Useref = () => {
const [name, setName] = useState("");
const previousName = useRef(null);
const handleChange = (event) => {
setName(event.target.value);
};
useEffect(() => {
previousName.current = name;
}, [name]);
return (
<div>
<input
onChange={handleChange}
value={name}
placeholder="Enter somethings"
/>
<div>
<h2>Current Value: {name}</h2>
<h2>Previous Value: {previousName.current}</h2>
</div>
</div>
);
};
Output:-

🎯 The differences between useRef & useState

Both preserve their data during
render cyclesandUI updates, but only theuseStateHook with its updater function causesre-rendersuseRefreturns anobjectwith acurrent propertyholding the actual value. In contrast,useStatereturns anarraywith two elements: the first item constitutes thestate, and the second item represents the stateupdater functionuseRef‘scurrent property ismutable, but useState‘s statevariablenot. In contrast to the current property ofuseRef, you should not directly assign values to the state variable ofuseState. Instead, always use theupdater function(i.e., the second array item). As the React team recommends in the documentation forsetStatein class-based components (but still true for function components), treat state like an immutable variableuseStateanduseRefcan be considered data Hooks, but onlyuseRefcan be used in yet another field of application: to gain direct access toReact components or DOM elements
🎯 When to use Refs and States

Refs are useful when getting user input, DOM element properties and storing constantly updating values.
If you are storing component related info or use methods in components states are the best option.
🎯 Wrap Up!!
I hope you learned something new🤗, if you wish to read more about these topics, you can refer to the resources below! You can also comment down your thoughts W3School







