Member-only story

useMemo vs. useCallback in React: Key Differences Explained

CodeByUmar
3 min readDec 11, 2024

Introduction

In React, useMemo and useCallback are hooks designed to optimize performance by memoizing values and functions. While they share some similarities, their purposes and use cases are distinct. In this blog, we’ll explore these hooks in detail, compare their functionalities, and clarify when to use each.

What is useMemo?

useMemo memoizes the return value of a function, recomputing it only when its dependencies change. It is primarily used for optimizing expensive computations to avoid recalculating them on every render.

Syntax:

const memoizedValue = useMemo(() => computeValue(a, b), [a, b]);

Example:

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

function ExpensiveComputation({ count }) {
const expensiveResult = useMemo(() => {
console.log('Computing...');
return count * 10;
}, [count]);
return <div>Result: {expensiveResult}</div>;
}
export default function App() {
const [count, setCount] = useState(1);
const [text, setText] = useState('');
return (
<div>
<ExpensiveComputation count={count} />
<button onClick={() => setCount(count + 1)}>Increment</button>
<input onChange={(e) => setText(e.target.value)}…

--

--

CodeByUmar
CodeByUmar

Written by CodeByUmar

Full Stack Developer sharing insights on JavaScript, React, and web development. Passionate coder and problem solver exploring new tech. 🚀

No responses yet