Enterprise Verified
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Optimization 8 min read • Chapter 25 of 26

React useMemo

Avoid recalculating expensive calculations on every render with the useMemo Hook.

The useMemo Hook returns a memoized value that only recalculates when one of the dependencies has changed.

Example

<!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 style="font-family:sans-serif;padding:20px;">
    <div id="root"></div>
    <script type="text/babel">
        function ExpensiveCalculation() {
            const [count, setCount] = React.useState(0);
            const calculation = React.useMemo(() => {
                let num = 0;
                for (let i = 0; i < 100000; i++) num += 1;
                return num;
            }, []);

            return (
                <div>
                    <h3>Expensive Result: {calculation}</h3>
                    <button onClick={() => setCount(c => c + 1)}>Re-render ({count})</button>
                </div>
            );
        }
        ReactDOM.createRoot(document.getElementById("root")).render(<ExpensiveCalculation />);
    </script>
</body>
</html>
Try it Yourself >> Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php

Community Q&A & Discussion

No questions yet. Be the first to start the discussion!
Enterprise Operations Suite

Streamline Employee Payroll & Attendance Operations

Eliminate manual spreadsheet errors. Integrate automated attendance tracking, EPF/ESI statutory calculations, and custom GST invoices.

Copied!

AI Learning Assistant

Ready to explain & guide

Hello! I am your MBS Digital AI Tutor. Ask me to explain concepts, review code, or suggest debugging steps.

Quick Starters:
AI Tutor is thinking...