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

useMemo Hook का उपयोग

useMemo React का एक hard math problem का answer याद रखना है ताकि उसे हर बार पूरी calculation दोहराना न पड़े।
Syntax
markup
const memoizedValue = useMemo(() => {
  return expensiveCalculation(dependency);
}, [dependency]);

Memoizing an Expensive Calculation

useMemo(calculateValue, dependencies) calculateValue run करता है और इसका result cache करता है। Future renders पर, अगर dependencies change नहीं हुई हैं, React recalculate करने के बजाय cached result reuse करता है, एक expensive computation की cost बचाते हुए।

Note: useMemo specifically तब उपयोग करें जब एक calculation measurably slow हो -- हर derived value के लिए default habit के रूप में नहीं।
Warning: useMemo फिर भी dependencies के हर unique set के लिए calculation एक बार run करता है -- यह पहली calculation को free नहीं बनाता, सिर्फ बाद वाली identical ones को।

उदाहरण: Memoizing an Expensive Calculation

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 ExpensiveList({ items }) {
      const sorted = React.useMemo(() => {
        console.log("Sorting...");
        return [...items].sort();
      }, [items]);
      return <ul>{sorted.map((item, i) => <li key={i}>{item}</li>)}</ul>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<ExpensiveList items={["banana", "apple", "cherry"]} />);
  </script>
</body>
</html>

How the Dependency Array Controls Recalculation

बिल्कुल useEffect जैसे, useMemo अपने second argument के रूप में एक dependency array लेता है। React हर dependency को इसकी previous value से compare करता है, और calculation function को सिर्फ तब re-run करता है जब last render के बाद से उनमें से कम से कम एक change हुई हो।

Note: हर उस value को list करें जिसे calculation function असल में पढ़ता है, वैसे ही जैसे आप useEffect के dependency array के लिए करते।
Warning: एक empty dependency array [] का मतलब है कि value सिर्फ एक बार calculate होती है, जो गलत है अगर calculation props या state पर depend करती है जो change हो सकती है।

उदाहरण: How the Dependency Array Controls Recalculation

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 PriceCalculator({ quantity, price }) {
      const total = React.useMemo(() => {
        console.log("Recalculating total...");
        return quantity * price;
      }, [quantity, price]);
      return <p>Total: ${total}</p>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<PriceCalculator quantity={3} price={9.99} />);
  </script>
</body>
</html>

When NOT to Use useMemo

Cheap calculations के लिए -- simple arithmetic, short string formatting -- useMemo की अपनी bookkeeping का overhead किसी भी benefit से ज़्यादा हो सकता है। useMemo genuinely expensive work के लिए एक targeted optimization tool है, हर derived value के लिए एक default wrapper नहीं।

Note: अगर आप sure नहीं कि एक calculation 'enough expensive' है या नहीं memoize करने के लिए, तो यह usually नहीं है -- useMemo सिर्फ एक actual performance problem notice करने के बाद जोड़ें।
Warning: Trivial calculations को हर जगह useMemo में wrap करना code को measurable performance gain के बिना पढ़ना harder बनाता है।

उदाहरण: When NOT to Use useMemo

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 SimpleGreeting({ name }) {
      // No useMemo needed here -- this is trivially cheap
      const greeting = `Hello, ${name}!`;
      return <p>{greeting}</p>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<SimpleGreeting name="Sam" />);
  </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. हर single calculation को useMemo में wrap करना, even cheap ones को, real benefit के बिना overhead जोड़ते हुए।
  2. Memoized calculation के अंदर उपयोग की गई एक value को dependency array में list करना भूल जाना।
  3. यह उम्मीद करना कि useMemo एक component को re-render होने से रोकेगा -- यह सिर्फ एक calculated VALUE memoize करता है, render को नहीं।
चैप्टर सारांश
  • useMemo renders के बीच एक expensive calculation का result cache करता है।
  • यह सिर्फ तब recalculate करता है जब इसकी listed dependencies में से एक change हो।
  • यह genuinely expensive computations के लिए है, default रूप से हर चीज़ optimize करने के लिए नहीं।
  • useMemo को overuse करना meaningful performance benefit के बिना complexity जोड़ सकता है।
ब्राउज़र सपोर्ट

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.