← Back to React Course | Chapter 5: Core Hooks | Lesson 6 of 12

useRef Hook का उपयोग

useRef एक sticky note है जो एक value को renders के बीच याद रखता है बिना कभी page को redraw cause किए जब यह change हो।
Syntax
markup
const refName = useRef(initialValue);

<element ref={refName} />

// Read or write without re-rendering
refName.current;

Accessing a DOM Element with useRef

एक ref object को किसी element के ref prop में pass करना आपको render होने के बाद असली DOM node तक direct access देता है, ref.current पर available। यह उन चीज़ों के लिए useful है जिनके लिए React में built-in prop नहीं है, जैसे एक input को programmatically focus करना।

Note: एक DOM element के लिए ref.current component render होने के बाद ही populate होता है -- इसे एक event handler या useEffect के अंदर access करें, render के दौरान नहीं।
Warning: Render body में directly (किसी effect या handler के अंदर नहीं) ref.current पढ़ना पहले render पर null होगा, DOM exist करने से पहले।

उदाहरण: Accessing a DOM Element with useRef

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function FocusInput() {
      const inputRef = React.useRef(null);
      return (
        <div>
          <input ref={inputRef} placeholder="Click button to focus me" />
          <button onClick={() => inputRef.current.focus()}>Focus Input</button>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<FocusInput />);
  </script>
</body>
</html>

Storing a Mutable Value Without Re-rendering

State के विपरीत, एक ref की .current value update करने से component re-render नहीं होता। यह refs को उन values store करने के लिए ideal बनाता है जिन्हें आपको track करना है, जैसे एक timer ID या एक previous value, बिना unnecessary UI updates trigger किए।

Note: उन values के लिए एक ref (state नहीं) उपयोग करें जिन्हें component को याद रखना चाहिए लेकिन जो खुद अपने आप कभी re-render cause नहीं करनी चाहिए।
Warning: अगर आपको चाहिए कि UI किसी value के change होने पर visually update हो, तो state उपयोग करें -- एक ref update अकेले यह नहीं करेगा।

उदाहरण: Storing a Mutable Value Without Re-rendering

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function ClickCounter() {
      const clicksRef = React.useRef(0);
      function handleClick() {
        clicksRef.current += 1;
        console.log("Clicked", clicksRef.current, "times (check console, no re-render)");
      }
      return <button onClick={handleClick}>Click me (see console)</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<ClickCounter />);
  </script>
</body>
</html>

useRef vs useState

दोनों एक value को renders के बीच persist करते हैं, लेकिन वे बहुत अलग purposes serve करते हैं: state changes UI में visible होने चाहिए और एक re-render trigger करने चाहिए, जबकि ref changes typically 'behind the scenes' bookkeeping होते हैं जिन्हें जो दिखाया जा रहा है उसे affect नहीं करना चाहिए।

सही वाला चुनना unnecessary re-renders और missing UI updates दोनों से बचाता है।

Note:
  • पूछें: 'क्या इस value के change होने पर screen update होनी चाहिए?'
  • अगर हां, तो state उपयोग करें।
  • अगर नहीं, तो एक ref उपयोग करें।
Warning: एक value के लिए ref उपयोग करना जो screen पर visible होनी चाहिए का मतलब है कि इसके change होने पर UI silently update नहीं होगा -- confusing bugs का एक common source।

उदाहरण: useRef vs useState

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function Comparison() {
      const [stateValue, setStateValue] = React.useState(0);
      const refValue = React.useRef(0);
      return (
        <div>
          <p>State (updates UI): {stateValue}</p>
          <button onClick={() => setStateValue(stateValue + 1)}>Update State</button>
          <button onClick={() => { refValue.current += 1; console.log("Ref is now", refValue.current); }}>Update Ref (check console)</button>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<Comparison />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक ref की .current value में change से एक re-render trigger होने की उम्मीद करना -- यह कभी नहीं होता।
  2. Render के दौरान ही एक DOM element ref के लिए ref.current पढ़ना, DOM असल में बनने से पहले।
  3. useRef को useState के साथ confuse करना -- refs उन values के लिए हैं जिन्हें re-renders cause करने की ज़रूरत नहीं, state उन values के लिए है जिन्हें ज़रूरत है।
चैप्टर सारांश
  • useRef एक single .current property वाला एक mutable object return करता है।
  • .current बदलना state के विपरीत re-render trigger NAHI करता।
  • एक common use DOM element को directly access करना है, ref prop के through।
  • एक और common use एक mutable value store करना है जो updates cause किए बिना renders के बीच persist करती है।
ब्राउज़र सपोर्ट

React 16.8 से available है, जब Hooks introduce हुए थे।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.