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

Dependency Array की जानकारी

Dependency array एक checklist है जो useEffect को exactly बताता है कि फिर से run करने का decide करने से पहले किन values को watch करना है।
Syntax
markup
useEffect(() => {
  // runs once after the first render
}, []);

useEffect(() => {
  // runs when value changes
}, [value]);

Running an Effect Once on Mount

Second argument के रूप में एक empty array [] pass करना React को बताता है कि इस effect की ऐसी कोई dependencies नहीं जिनकी वजह से इसे re-run करना पड़े -- तो यह सिर्फ एक बार, component के पहले render के ठीक बाद run होता है।

यह commonly one-time setup के लिए उपयोग होता है जैसे initial data fetch करना।

Note: एक empty dependency array 'component दिखने पर एक बार run करो' behavior replicate करने का standard तरीका है।
Warning: अगर आपका effect असल में एक prop या state value उपयोग करता है लेकिन आप फिर भी [] pass करते हैं, तो वह value effect के अंदर अपनी initial value पर stuck रह जाएगी (एक stale closure)।

उदाहरण: Running an Effect Once on Mount

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 WelcomeOnce() {
      React.useEffect(() => {
        console.log("This runs only once, when the component first appears.");
      }, []);
      return <p>Check the console -- the message logs only once.</p>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<WelcomeOnce />);
  </script>
</body>
</html>

Re-running When a Value Changes

Dependency array में एक variable list करना React को इसे renders के बीच compare करने और effect को सिर्फ तब re-run करने को बताता है जब यह पहले से अलग हो।

यह आपको specifically एक piece of state या props में changes के response में react करने देता है, unrelated re-renders को ignore करते हुए।

Note: Component scope से हर वह value शामिल करें जिसे effect असल में उपयोग करता है -- यह effect को सही तरीके से उसके साथ sync में रखता है जिस पर यह depend करता है।
Warning: Effect जिस value का उपयोग करता है उसे list करना भूल जाना सबसे common React bugs में से एक है -- ESLint का react-hooks plugin इनमें से ज़्यादातर अपने आप पकड़ लेता है।

उदाहरण: Re-running When a Value Changes

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 UserWatcher({ userId }) {
      React.useEffect(() => {
        console.log("Fetching data for user:", userId);
      }, [userId]);
      return <p>Watching user {userId}</p>;
    }
    function App() {
      const [id, setId] = React.useState(1);
      return <div><UserWatcher userId={id} /><button onClick={() => setId(id + 1)}>Next User</button></div>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

No Dependency Array vs Empty Array

ये दो forms similar दिखते हैं लेकिन बहुत अलग तरीके से behave करते हैं: array को पूरी तरह omit करना हर render के बाद effect run करता है, जबकि एक empty array [] pass करना इसे सिर्फ एक बार run करता है।

इन दोनों को confuse करना bugs का एक frequent source है -- एक excessive re-running cause करता है, दूसरा stale data cause कर सकता है।

Note: अगर आप sure नहीं कि कौन सा उपयोग करें, तो दो extremes में से एक default करने के बजाय उन actual values को list करने से शुरू करें जो आपका effect पढ़ता है।
Warning: Array को पूरी तरह miss करना (even एक empty array भी नहीं) accidentally करना आसान है और silently आपके effect की behavior बदल देता है।

उदाहरण: No Dependency Array vs Empty Array

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 [count, setCount] = React.useState(0);
      React.useEffect(() => { console.log("Runs every render"); });
      React.useEffect(() => { console.log("Runs once only"); }, []);
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    }
    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. Effect के अंदर उपयोग किए गए variable को dependency array से बाहर छोड़ना, जिससे यह एक stale value उपयोग करता है।
  2. एक empty array [] pass करना जब effect असल में props या state पर depend करता है, real bugs hide करते हुए।
  3. Dependency array में एक नया बनाया गया object या array literal डालना, जिससे effect हर render re-run होता है क्योंकि यह कभी पिछले वाले के बराबर नहीं होता।
चैप्टर सारांश
  • Dependency array useEffect का second argument है।
  • React effect को सिर्फ तब re-run करता है जब listed values में से एक last render के बाद से change हुआ हो।
  • एक empty array [] का मतलब है कि effect सिर्फ एक बार, पहले render के बाद run होता है।
  • Array को पूरी तरह omit करना effect को हर render के बाद run करता है।
ब्राउज़र सपोर्ट

कोई browser-specific restrictions नहीं -- dependency array behavior Hooks के React 16.8 में introduction से consistent है।

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.