Home About Skills Products Work
Projects Services Experience
Learn
Tutorials Courses Blogs Resources
Contact
Tutorials · React JS

useMemo and useCallback - Performance Optimization

useMemo and useCallback - Performance Optimization

Every re-render runs a component's function body from scratch — meaning any expensive calculations and new function objects inside it get recreated too. useMemo and useCallback give you a way to "cache" both of those things.

useMemo — Memoizing a Value

function ProductList({ products, searchTerm }) {
  const filteredProducts = useMemo(() => {
    console.log('Filtering...'); // only runs when products/searchTerm change
    return products.filter(p =>
      p.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [products, searchTerm]);

  return (
    <ul>
      {filteredProducts.map(p => <li key={p.id}>{p.name}</li>)}
    </ul>
  );
}

Without useMemo, this filtering would run on every render — even when an unrelated piece of state (like a modal opening/closing) changed. useMemo "remembers" the result as long as the dependencies stay the same.

useCallback — Memoizing a Function Reference

function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    console.log('clicked');
  }, []); // empty deps = the same function reference on every render

  return <ExpensiveChild onClick={handleClick} />;
}

const ExpensiveChild = React.memo(function ExpensiveChild({ onClick }) {
  console.log('ExpensiveChild rendered');
  return <button onClick={onClick}>Click</button>;
});

Without useCallback, handleClick would be a new function object on every render — causing the React.memo-wrapped ExpensiveChild to re-render unnecessarily (since its prop "looks" different). useCallback keeps the reference stable.

Avoid Overusing Them

These hooks aren't free either — they have their own memory and comparison cost. Only use them when:

  • The calculation is genuinely expensive (large arrays, complex math).
  • A function is being passed to a React.memo child, or is a dependency of another hook.

Wrapping every small calculation in useMemo doesn't improve performance — it just makes the code more complex.

Key Takeaways

  • useMemo — caches a computed value.
  • useCallback — caches a function reference.
  • Only use them when there's a measurable performance problem, not "just in case."
What is React? JSX Introduction and Your First Component

What is React? JSX Introduction and Your First Component

What problem React actually solves, how JSX syntax works, and how to build your first component.

Setting Up a React App with Vite

Setting Up a React App with Vite

Set up a modern React project in seconds with Vite, and understand the resulting folder structure.

Understanding Components and Props

Understanding Components and Props

Build functional components and pass data from parent to child components using props.

Esc