
What is useRef in React
What is useRef in React: The useRef hook in React is a built-in hook that provides a way to persist values across renders without triggering a re-render. It is commonly used to directly access and manipulate DOM elements, store mutable values, or hold references to components or variables that should not cause re-renders when updated.
Syntax:
const ref = useRef(initialValue);
initialValue: The initial value you want to store in the ref.
ref: The useRef hook returns an object with a .current property that holds the value you want to persist.
Key Features of useRef:
Persist State Between Renders:
Unlike state variables, updating a value in useRef does not cause the component to re-render.
Mutable Container:
The value stored in useRef is mutable and can be changed at any time without triggering a render.
Storing Mutable Variables Without Re-Renders:
import React, { useRef, useState } from 'react';
function Timer() {
const countRef = useRef(0); // Store the timer count
const [render, setRender] = useState(false); // Force re-render (optional)
const incrementCount = () => {
countRef.current += 1; // Increment the count without triggering re-render
console.log(`Count: ${countRef.current}`);
};
const forceRender = () => setRender(!render); // Force re-render to see count updates
return (
<div>
<button onClick={incrementCount}>Increment Count</button>
<button onClick={forceRender}>Force Render</button>
<p>Count (on re-render): {countRef.current}</p>
</div>
);
}
export default Timer;
Explanation:
countRef stores the count value without causing the component to re-render when updated.
The forceRender button forces the component to re-render, showing the updated value of countRef.current.
When to Use useRef:
To store a mutable value that does not trigger re-renders (e.g., timers, counters, previous values).
To persist a value across renders without needing state
Comments