Chapter 10React Tutorial~1 min read
useRef Hook
useRef — DOM Access आणि Mutable Values
useRef एक mutable container देतो ज्याचे .current property बदलता येते. Re-render trigger होत नाही. DOM elements directly access करायला (focus, scroll, measure) आणि renders मध्ये values persist करायला वापरतात.
DOM Access — Input Focus
useRef — input element access
jsx
import { useRef } from 'react';
function SearchBox() {
const inputRef = useRef(null); // initial value null
function focusInput() {
inputRef.current.focus(); // DOM element directly access
}
function clearInput() {
inputRef.current.value = "";
inputRef.current.focus();
}
return (
<div>
{/* ref prop — React element ला ref attach करतो */}
<input ref={inputRef} placeholder="Search करा..." />
<button onClick={focusInput}>Focus</button>
<button onClick={clearInput}>Clear</button>
</div>
);
}Ref vs State — फरक
Ref — re-render नाही, State — re-render होतो
jsx
import { useState, useRef } from 'react';
function RenderCounter() {
const [count, setCount] = useState(0);
const renderCount = useRef(0); // renders मध्ये persist होतो
// प्रत्येक render वर increment — re-render trigger नाही
renderCount.current += 1;
return (
<div>
<p>State count: {count}</p>
<p>Component renders: {renderCount.current}</p>
<button onClick={() => setCount(c => c + 1)}>
State वाढवा (Re-render!)
</button>
</div>
);
}Timer Ref — Cleanup साठी
Timer ID store करणे
jsx
import { useState, useRef } from 'react';
function StopWatch() {
const [time, setTime] = useState(0);
const [running, setRunning] = useState(false);
const timerRef = useRef(null); // timer ID store करतो
function start() {
setRunning(true);
timerRef.current = setInterval(() => {
setTime(t => t + 1);
}, 1000);
}
function stop() {
setRunning(false);
clearInterval(timerRef.current); // timer बंद करतो
}
function reset() {
stop();
setTime(0);
}
return (
<div>
<p>{time}s</p>
<button onClick={start} disabled={running}>Start</button>
<button onClick={stop} disabled={!running}>Stop</button>
<button onClick={reset}>Reset</button>
</div>
);
}✅ Key Points — लक्षात ठेवा
- ▸const ref = useRef(null) — mutable container
- ▸ref.current — actual value access करतो
- ▸ref बदलल्यावर re-render नाही — state पेक्षा वेगळे
- ▸<input ref={inputRef} /> — DOM element attach
- ▸inputRef.current.focus() — DOM API directly call
0/12 chapters पूर्ण