What is Use Memo In React

In this article, we will learn how to use useMemo hook in React.

  • The useMemo hook returns a memoized value that is utilised in the functional component of react.
  • Consider memoization to be the act of storing a value such that it does not have to be recalculated.
  • When one of its dependents updates, the useMemo Hook fires.
  • This can help you perform better.
  • UseMemo and useCallback are comparable hooks. UseMemo returns a memoized value, whereas useCallback returns a memoized function.

Syntax:

const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies)
  • useMemo(compute, dependencies) runs compute during initial rendering, memoizes the computation result, and provides it to the component.
  • If during next renderings the dependencies don’t change, then useMemo() doesn’t invoke compute but returns the memoized value.
  • But if dependencies change during re-rendering, then useMemo() invokes compute, memoizes the new value, and returns it.

My page will look like this:

import { useState, useMemo } from "react";

export default function App() {
    const [count, setCount] = useState(0);

    const [wordIndex, setWordIndex] = useState(0);

    const words = ["hey", "this", "is", "cool", "hello"];

    const word = words[wordIndex];

    const computeLetterCount = (word) => {
        let i = 0;
        while (i < 1000000000) i++;
        return word.length;
    };

    const letterCount = useMemo(() => computeLetterCount(word), [word]);

    return (
        <div style={{ padding: "15px" }}>
            <h2>Compute number of letters (slow 🐌)</h2>
            <p>
                "{word}" has {letterCount} letters
            </p>
            <button onClick={() => {
                const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1;
                setWordIndex(next);
            }}
            >
                Next word
            </button>
            <h2>Increment a counter (fast ⚡️)</h2>
            <p>Counter: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

In the above code if I click on the increase counter button then it runs event of increment of count but it also runs increment number.

Output:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories