The useMemo Hook returns a memoized value that only recalculates when one of the dependencies has changed.
React Frontend Framework
React Tutorial
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.
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
Verified
No questions yet. Be the first to start the discussion!