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

Hooks में आम गलतियाँ

Common Hook mistakes वही कुछ banana peels हैं जिन पर almost हर React beginner कम से कम एक बार slip करता है -- उन्हें पहले से जानना आपको उनके around step करने में मदद करता है।

Mistake: Missing Dependencies

जब एक effect, memo, या callback component scope से एक value उपयोग करता है लेकिन इसे dependency array में list नहीं करता, तो वह value freeze हो जाती है जो भी वह render पर थी जब Hook पहली बार setup हुआ था -- एक bug जिसे stale closure कहा जाता है।

Note: ESLint react-hooks plugin के exhaustive-deps rule को आपका guide होने दें -- यह missing dependencies automatically flag करता है।
Warning: एक missing dependency immediate error cause नहीं करता -- यह silently outdated behavior produce करता है जो बहुत बाद तक notice करना hard हो सकता है।

उदाहरण: Mistake: Missing Dependencies

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 StaleExample() {
      const [count, setCount] = React.useState(0);
      React.useEffect(() => {
        const id = setInterval(() => {
          console.log("Count is", count); // stale! always logs the initial value
        }, 1000);
        return () => clearInterval(id);
      }, []); // missing 'count' dependency
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<StaleExample />);
  </script>
</body>
</html>

Mistake: Conditional Hook Calls

एक Hook call को एक if statement के अंदर रखने का मतलब है कि यह कुछ renders पर skip हो सकता है लेकिन दूसरों पर नहीं, React की इस assumption को तोड़ते हुए कि Hooks हर बार same order में call होते हैं।

यह confusing errors produce करता है जो अक्सर clearly असली cause की तरफ point नहीं करते।

Note: Conditional logic को Hook call के around रखने के बजाय Hook के अंदर move करें (जैसे एक effect body के अंदर)।
Warning: यह mistake अक्सर cryptic error 'Rendered more hooks than during the previous render.' produce करती है।

उदाहरण: Mistake: Conditional Hook Calls

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 FixedVersion({ showExtra }) {
      const [count, setCount] = React.useState(0); // always called
      const [extra, setExtra] = React.useState(0); // always called, even if unused
      return <button onClick={() => setCount(count + 1)}>{count}{showExtra ? ` (extra: ${extra})` : ""}</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<FixedVersion showExtra={true} />);
  </script>
</body>
</html>

Mistake: Mutating State Directly

State में एक array या object को directly modify करना (जैसे एक state array पर .push() call करना) reference को unchanged छोड़ सकता है, तो React detect नहीं कर पाए कि कुछ changed है और re-rendering skip कर दे।

Object या array state update करते समय हमेशा एक नई copy बनाएं।

Note: Object/array state update करते समय spread operator (...) या वे array methods उपयोग करें जो नई arrays return करते हैं (.map, .filter)।
Warning: यह mistake खासतौर पर sneaky है क्योंकि data technically memory में DID change हुआ -- सिर्फ इतना कि React का change-detection इसे notice नहीं कर पाया।

उदाहरण: Mistake: Mutating State Directly

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 TagList() {
      const [tags, setTags] = React.useState(["react"]);
      function addTag() {
        setTags([...tags, "hooks"]); // correct: new array via spread
      }
      return (
        <div>
          <ul>{tags.map((t, i) => <li key={i}>{t}</li>)}</ul>
          <button onClick={addTag}>Add Tag</button>
        </div>
      );
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<TagList />);
  </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. useEffect/useMemo/useCallback के dependency array में एक dependency भूल जाना, stale values की ओर ले जाते हुए।
  2. Hooks को conditionally call करना, React के required consistent call order को तोड़ते हुए।
  3. नई copies बनाने के बजाय directly state (arrays/objects) mutate करना updates से पहले।
चैप्टर सारांश
  • ज़्यादातर Hook bugs एक छोटे, well-known set of common mistakes से आते हैं।
  • Stale closures तब होते हैं जब एक effect के array से एक dependency missing हो।
  • Conditional Hook calls Rules of Hooks violate करते हैं और runtime errors cause करते हैं।
  • ESLint react-hooks plugin इनमें से कई mistakes automatically पकड़ता है।
ब्राउज़र सपोर्ट

ये mistakes और इनके fixes React 16.8 में इनके introduction से सभी Hooks पर apply होते हैं।

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.