When learning React, we often use useState to manage data. But sometimes we need to store a value or access a DOM element without re-rendering the component.
That’s where useRef comes in.
*In this blog, let’s understand what useRef is, why we need it, and how to use it, with simple examples.
*
🔹 What is useRef?
useRef is a React Hook that allows you to:
- Access DOM elements directly
- Store values that do not cause re-render when changed
Simple definition:
useRef is used to remember a value or reference a DOM element without triggering a re-render.
🔹 Syntax of useRef
const myRef = useRef(initialValue);
- useRef() returns an object
- The value is stored inside .current
- myRef.current
🔹 Why useRef is needed?
In React:
- useState → updates UI and re-renders component
- useRef → stores value but does NOT re-render
This makes useRef useful for:
- Accessing input fields
- Focusing elements
- Storing previous values
- Timers and intervals
🔹 Example 1: Accessing DOM Element (Focus Input)
`import { useRef } from "react";
function App() {
const inputRef = useRef(null);
const handleFocus = () => {
inputRef.current.focus();
};
return (
<>
Focus Input
</>
);
}
export default App;`
Explanation:
- inputRef stores the input element
- inputRef.current points to the actual DOM node
- Clicking the button focuses the input field
🔹 Example 2: useRef vs useState
`import { useRef, useState } from "react";
function Counter() {
const refCount = useRef(0);
const [stateCount, setStateCount] = useState(0);
return (
<>
State Count: {stateCount}
Ref Count: {refCount.current}
<button onClick={() => setStateCount(stateCount + 1)}>
Increase State
</button>
<button onClick={() => refCount.current += 1}>
Increase Ref
</button>
</>
);
}`
Key Difference:
- useState → UI updates
- useRef → UI does not update automatically
Top comments (0)