-
ReactJS useRef Hook
-
In React, not every value needs to update the UI when it changes. Some values only need to be remembered or used internally, without triggering a re-render. The
useRefHook exists exactly for these situations.
What Is useRef?
In simpler words:useRefis a React Hook that allows you to store a value that persists across renders without causing the component to re-render when it changes.
It returns an object with a single property:useRefis used to remember values between renders without updating the UI.{ current: value }
Why Does React Need useRef?
React components are just functions.
Because of this:
Every time a component re-renders, the function runs again from the top.- normal variables reset on every render
- state values are tracked and trigger re-renders
- a value that should not reset
- a value that should not cause re-render
- direct access to a DOM element
useRefsolves all of these problems.
Importing useRef
import { useRef } from "react";
Basic Syntax of useRef
const myRef = useRef(initialValue);initialValueis set only once (on first render)- the value is stored in
myRef.current - updating
myRef.currentdoes not re-render the component
Accessing DOM Elements (Most Common Use Case)
React does not encourage direct DOM access using
Example: Focus an Input Fielddocument.getElementById.
Instead, it provides useRef for safe DOM interaction.
Explanationimport { useRef } from "react"; function FocusInput() { const inputRef = useRef(null); function handleFocus() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleFocus}> Focus Input </button> </> ); } export default FocusInput;- React stores the input element in inputRef.current
- You can call DOM methods safely
- UI does not re-render
When You Should Use useRef
Use
useRefwhen you need to:- access DOM elements
- store mutable values
- remember previous state
- avoid unnecessary re-renders
- Scroll to a Section
- Prevent Multiple API Calls
Final Summary
The
useRefHook allows React components to store values that persist across renders without triggering UI updates. It is commonly used for DOM access, tracking previous values, managing timers, and storing internal mutable data. UnderstandinguseRefhelps you write more efficient and predictable React components by avoiding unnecessary re-renders.