Open In App

Difference between React.memo() and useMemo() in React.

In React applications, optimizing performance is crucial for delivering a smooth user experience. Two key tools for achieving this are React.memo() and useMemo(). While both help improve performance, they serve different purposes and are used in distinct scenarios.

What is React.memo() ?

React.memo() is a higher-order component (HOC) provided by React that memoizes functional components. It means that it caches the result of the component’s rendering based on its props, and re-renders only when the props have changed.



Syntax of React.memo():

const MemoizedComponent = React.memo(FunctionalComponent);

Features of React.memo():

Example of React.memo()

Example: Below is the code example for the React.memo().




import React from 'react';
 
// Functional component
const MyComponent = React.memo((props) => {
    console.log('Rendering MyComponent');
    return (
        <div>
            <h1>Hello, {props.name}!</h1>
            <p>{props.message}</p>
        </div>
    );
});
 
// Parent component
function App() {
    const [count, setCount] = React.useState(0);
 
    // Handler to update count
    const handleClick = () => {
        setCount(count + 1);
    };
 
    return (
        <div>
            <button onClick={handleClick}>
                Update Count
            </button>
            <MyComponent name="React"
                message="Welcome to React world!" />
        </div>
    );
}
 
export default App;

Step to run the app:

npm start

Output:

What is useMemo() ?

useMemo() is a React Hook used to memoize the result of expensive computations within functional components. It memorizes the value returned by a provided function and re-calculates it only when the dependencies change.

Syntax of useMemo():

const memoizedValue = useMemo(() => computeExpensiveValue(dep1, dep2), [dep1, dep2]);

Features of useMemo():

Example of useMemo()

Example: Below is the code example for the use.memo().




//App.js
 
import React,
{
    useState,
    useMemo
} from 'react';
 
const WithMemo = () => {
    const [count, setCount] = useState(0);
    const [renderCount, setRenderCount] = useState(0);
 
    const computeExpensiveValue = (num) => {
        console.log("Computing...");
        let result = 0;
        for (let i = 0; i < 1000000000; i++) {
            result += num;
        }
        return result;
    };
 
    // Using useMemo to memoize the result based on count
    const result = useMemo(
        () =>
            computeExpensiveValue(count), [count]
    );
 
    return (
        <div>
            <h2>With Memo Example</h2>
            <p>Count: {count}</p>
            <p>Result: {result}</p>
            <p>Render Count: {renderCount}</p>
            <button
                onClick={
                    () => setCount(count + 1)
                }>
                Increment Count
            </button>
            <button onClick={
                () =>
                    setRenderCount(renderCount + 1)
            }>
                Increment Render Count
            </button>
        </div>
    );
};
 
export default WithMemo;

Step to run the app:

npm start

Output:

Difference Between React.memo() and useMemo():

Feature

React.memo()

useMemo()

Purpose

Memoizes functional components

Memoizes the result of expensive computations

Dependency

Props

Custom dependencies array

Syntax

HOC wrapping

Hook invocation

Return Value

Memoized component

Memoized value

Typical Use Case

Memoizing functional components based on props

Memoizing expensive computations

Conclusion:

React.memo() and useMemo() are essential tools for optimizing React applications. While React.memo() focuses on memoizing functional components to prevent unnecessary re-renders based on props, useMemo() is used to memoize expensive computations within functional components. Understanding their differences and appropriate usage is key to effectively improving performance in React applications.


Article Tags :