Open In App

How useMemo Hook optimizes performance in React Component ?

The useMemo hook in React optimizes performance by memoizing the result of a function and caching it. This caching ensures that expensive computations inside the useMemo callback are only re-executed when the dependencies change, preventing unnecessary recalculations and improving the rendering performance of the component.

How useMemo Hook Optimizes Performance ?

By memoizing the result of a function computation, 'useMemo' helps prevent unnecessary re-execution of expensive computations in a React component. This optimization avoids redundant calculations during renders, improving performance, especially with complex computations and large components.

Approach to implement useMemo Hook in React Component:

Example: The below example calculates the factorial of a number.

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

const FactorialCalculator = () => {
    const [number, setNumber] = useState(0)
    const [count, setCount] = useState(0);

    const calculateFactorial = (num) => {
        console.log(`Calculating factorial of ${num}`);
        let result = 1;
        for (let i = 2; i <= num; i++) {
            result *= i;
        }
        return result;
    };

    const factorial = useMemo(
        () => calculateFactorial(number), [number]);

    return (
        <div>
            <h2>Factorial Calculator</h2>
            <p>Number:{number} </p>
            <p>Factorial: {factorial}</p>
            <button onClick={
                () => setNumber(number + 1)}>Next factorial
            </button>
            <hr />
            <p>Count: {count}</p>
            <button onClick={
                () => setCount(count + 1)}>Increment Count
            </button>

        </div>
    );
};

export default FactorialCalculator;

Output:

Untitled-design-26-ezgifcom-crop

Conclusion:

The 'useMemo' hook in React is a powerful tool for optimizing performance by memoizing the result of a function computation. By using `useMemo`, you can prevent unnecessary re-renders of components and improve the overall efficiency of your React applications. Incorporating `useMemo` into your components can lead to smoother user experiences and better performance, especially in scenarios where heavy computations are involved.

Article Tags :