Hackforge Academy

Category: react

useMemo vs useCallback: Quick Difference

Published on 27 Oct 2026

Explanation

useMemo caches the result of calling a function. useCallback caches the function itself. Both re-evaluate or change their cached value when a dependency changes.

Code:

const total = useMemo(() => calculateTotal(items), [items]);

const handleClick = useCallback(() => {
  console.log('Clicked');
}, []);

Explanation

Use useMemo when a calculation is expensive and its inputs often remain unchanged between renders. Measure performance first; ordinary inexpensive calculations generally do not need memoization.

Code:

const filteredProducts = useMemo(() => {
  return products.filter((product) =>
    product.name.toLowerCase().includes(query.toLowerCase())
  );
}, [products, query]);

Explanation

Use useCallback when a stable function reference helps a memoized child avoid unnecessary rerenders or when the function is a dependency of another Hook.

Code:

const onSelect = useCallback((id) => {
  setSelectedId(id);
}, []);

return <ProductList products={products} onSelect={onSelect} />;

Explanation

An object literal created during render gets a new identity each time. useMemo can preserve the object identity until its dependencies change, which can help memoized children or effect dependencies.

Code:

const searchOptions = useMemo(() => ({
  matchMode: 'whole-word',
  query
}), [query]);

useEffect(() => {
  search(searchOptions);
}, [searchOptions]);

Explanation

Memoization is a performance optimization, not a correctness guarantee. Prefer straightforward code first, then add useMemo or useCallback where profiling or component behavior shows a meaningful benefit.

Code:

function Price({ amount, taxRate }) {
  // Simple calculation: memoization is probably unnecessary.
  const total = amount + amount * taxRate;
  return <p>{total.toFixed(2)}</p>;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community