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

Hooks और Class Lifecycle Methods में अंतर

Hooks एक function component को वह सब करने देते हैं जो एक class component कर सकता था, ज़्यादा ceremonial class syntax के बजाय simple functions उपयोग करके।
Syntax
markup
// Class component
class ClassName extends React.Component {
  state = { value: initial };
  componentDidMount() {}
  render() { return <div />; }
}

// Function component with Hooks
function FunctionName() {
  const [value, setValue] = useState(initial);
  useEffect(() => {}, []);
  return <div />;
}

State: this.state vs useState

एक class component state को this.state पर एक object के रूप में store करता है और इसे this.setState() के through update करता है, जो दिए गए fields को existing state object में merge करता है। useState इसके बजाय आपको हर call के लिए एक independent state variable और setter pair देता है, और objects को automatically merge NAHI करता।

Note: अगर आप class code को Hooks में translate कर रहे हैं, याद रखें कि हर this.state field अक्सर इसका अपना separate useState call बन जाता है।
Warning: this.setState के विपरीत, एक object के साथ useState setter call करना पूरी value को REPLACE करता है -- यह इसे automatically previous object के साथ merge नहीं करता।

उदाहरण: State: this.state 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">
    // Hooks version
    function Counter() {
      const [count, setCount] = React.useState(0);
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<Counter />);
  </script>
</body>
</html>

Lifecycle Methods vs useEffect

Class components side-effect logic को कई lifecycle methods में split करते हैं: componentDidMount (एक बार run होता है), componentDidUpdate (updates पर run होता है), और componentWillUnmount (हटाए जाने पर run होता है)। useEffect इन तीनों roles को एक Hook में combine करता है, इसके dependency array और optional cleanup function से differentiated।

Note: [] वाला एक effect लगभग componentDidMount + componentWillUnmount combined से match करता है; dependencies वाला एक effect लगभग componentDidUpdate से भी match करता है।
Warning: useEffect और lifecycle methods के बीच match close है लेकिन perfect नहीं -- effect timing (paint के बाद) componentDidMount की timing से थोड़ा अलग है।

उदाहरण: Lifecycle Methods vs useEffect

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 MountLogger() {
      React.useEffect(() => {
        console.log("Like componentDidMount");
        return () => console.log("Like componentWillUnmount");
      }, []);
      return <p>Check the console.</p>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<MountLogger />);
  </script>
</body>
</html>

Why Function Components Are Now Preferred

Hooks function components को class components जो भी कर सकते हैं वो सब करने देते हैं, कम boilerplate के साथ (कोई constructor नहीं, कोई this binding issues नहीं) और custom Hooks के through logic reuse करना आसान।

इसकी वजह से, official React docs और ज़्यादातर नए projects classes के बजाय Hooks वाले function components को favor करते हैं।

Note: आज एक नया React project शुरू करते समय, Hooks वाले function components को default मानें -- class components को सिर्फ existing legacy code maintain करने के लिए reserve करें।
Warning: this binding issues (जैसे event handlers अपना this context खो देना) एक common class-component pitfall है जिससे Hooks पूरी तरह बचते हैं।

उदाहरण: Why Function Components Are Now Preferred

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 ModernComponent() {
      const [liked, setLiked] = React.useState(false);
      return <button onClick={() => setLiked(!liked)}>{liked ? "Liked!" : "Like"}</button>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<ModernComponent />);
  </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. यह assume करना कि Hooks और class lifecycle methods हर detail में one-to-one map होते हैं -- कुछ behaviors (जैसे effect timing) subtly अलग हैं।
  2. Class-based patterns (जैसे this.state) को गलती से एक function component में mix करना।
  3. यह मानना कि class components deprecated या unsupported हैं -- वे अब भी fine काम करते हैं, सिर्फ नए code के लिए recommended style नहीं हैं।
चैप्टर सारांश
  • Hooks function components को state और दूसरे React features उपयोग करने देते हैं जो पहले सिर्फ classes में available थे।
  • useState this.state/this.setState को replace करता है।
  • useEffect ज़्यादातर componentDidMount, componentDidUpdate, और componentWillUnmount combined के uses को replace करता है।
  • Hooks वाले Function components अब React में recommended default हैं।
ब्राउज़र सपोर्ट

Hooks React 16.8 में introduce हुए थे; class components React 18 में पूरी तरह supported रहते हैं।

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.