How To Use useMemo Hook In React? See Example

The useMemo hook memoizes a computed value, preventing recalculation on every render.
It’s used to optimize performance for expensive computations.


Basic Syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • Computes value only when dependencies change
  • Returns memoized result

Example: Expensive Computation

import React, { useState, useMemo } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [other, setOther] = useState(0);

  const expensiveCalculation = useMemo(() => {
    console.log("Calculating...");
    return count * 2;
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <h2>Expensive Result: {expensiveCalculation}</h2>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <button onClick={() => setOther(other + 1)}>Increment Other</button>
    </div>
  );
}

export default App;

✅ Expensive calculation only runs when count changes, not other.


Key Points

  • Memoizes computed values
  • Optimizes performance for expensive computations
  • Runs only when dependencies change
  • Useful for large lists, calculations, or derived data

Conclusion

useMemo helps React apps perform better by avoiding unnecessary recalculations, keeping components efficient.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *