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

Hooks के Rules

Rules of Hooks एक recipe की उस instruction जैसे हैं जो हमेशा हर बार same order में ingredients add करने को कहती है -- एक step skip करें, और पूरी dish गलत बन जाती है।
Syntax
markup
function Component() {
  // Top level only: not inside if, loops or nested functions
  const [state, setState] = useState(initial);
  useEffect(() => {}, []);

  return <div />;
}

Rule 1: Only Call Hooks at the Top Level

Hooks को हर single render में same order में call किया जाना चाहिए -- React internally इस call order का उपयोग हर Hook call को इसकी correct state से associate करने के लिए करता है।

एक Hook को एक condition या loop के अंदर रखना renders के बीच यह order बदल सकता है, React की internal bookkeeping corrupt करते हुए।

Note: अगर आपको conditional behavior चाहिए, condition को Hook call के around रखने के बजाय Hook के INSIDE रखें (जैसे useEffect के function body के अंदर)।
Warning: if (condition) { const [x] = useState(0); } जैसा code इस rule को तोड़ता है और confusing, hard-to-diagnose bugs cause करता है।

उदाहरण: Rule 1: Only Call Hooks at the Top Level

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 Correct({ show }) {
      const [count, setCount] = React.useState(0); // always called, unconditionally
      if (!show) return null; // conditional logic AFTER the Hook call
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<Correct show={true} />);
  </script>
</body>
</html>

Rule 2: Only Call Hooks from React Functions

Hooks को सिर्फ एक React function component के अंदर से या एक custom Hook के अंदर से (use से शुरू होने वाले नाम का एक function) call किया जाना चाहिए।

उन्हें एक regular utility function या एक class component के methods से call करना supported नहीं है और errors cause करेगा।

Note: एक custom Hook सिर्फ एक regular function है जो दूसरे Hooks call करता है -- इसका नाम use से शुरू करें ताकि React और दूसरे developers दोनों इसे एक के रूप में recognize करें।
Warning: एक plain helper function से (कोई component नहीं, कोई Hook नहीं) useState call करना एक 'Invalid hook call' error throw करता है।

उदाहरण: Rule 2: Only Call Hooks from React Functions

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 useDoubled(value) { // valid custom Hook -- starts with "use"
      return React.useMemo(() => value * 2, [value]);
    }
    function Display({ n }) {
      const doubled = useDoubled(n);
      return <p>{n} doubled is {doubled}</p>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<Display n={5} />);
  </script>
</body>
</html>

Enforcing the Rules with ESLint

Official eslint-plugin-react-hooks package दोनों rules की violations को directly आपके editor में automatically flag करता है, आप code run करने से पहले ही ज़्यादातर mistakes पकड़ते हुए।

Almost हर modern React project setup (Create React App, Vite templates) इस plugin को default रूप से include करता है।

Note: react-hooks ESLint plugin को enabled रखें -- यह subtle mistakes पकड़ता है जो सिर्फ code पढ़कर miss करना आसान है।
Warning: Hooks rules के लिए ESLint warnings को 'एक error गायब करने' के लिए disable करना usually मतलब है कि एक real bug fix नहीं हो रहा, सिर्फ hide हो रहा है।

उदाहरण: Installing the ESLint Hooks Plugin

bash
$ npm install --save-dev eslint-plugin-react-hooks

// .eslintrc.json
{
  "plugins": ["react-hooks"],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

⚠️ Run this in your own terminal or Node.js environment.

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. Component के top level पर call करने के बजाय एक if statement, loop, या nested function के अंदर एक Hook call करना।
  2. एक React component या दूसरे custom Hook के बजाय एक regular JavaScript function से Hooks call करना।
  3. Renders के बीच Hook calls को reorder करना या conditionally skip करना, जो React की internal tracking तोड़ता है।
चैप्टर सारांश
  • Hooks को हमेशा एक component के top level पर call किया जाना चाहिए, कभी conditions या loops के अंदर नहीं।
  • Hooks को सिर्फ React function components या दूसरे custom Hooks से call किया जाना चाहिए।
  • React depend करता है कि Hooks हर render पर exact same order में call हों।
  • eslint-plugin-react-hooks package automatically ज़्यादातर rule violations पकड़ता है।
ब्राउज़र सपोर्ट

ये rules React 16.8 से introduce हुए सभी 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.