
what is useRef() ?
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:
- Access or reference DOM elements directly
- Store mutable values that persist across renders (without causing re-renders)
Syntax
const myRef = useRef(initialValue);
- myRef.current stores the value
- 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
Feature | Description |
---|---|
useRef() | Stores a persistent value across renders |
ref.current | Access the value or DOM node |
Doesn’t re-render | Updating ref.current does not trigger re-render |
Common use | DOM access, timers, previous value, local counters |
Comments
Add new comment