This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Usage of useMemo hook in React




Intro

All through my expertise engaged on varied initiatives at my present firm, I’ve gained a wealth of information about React.js, which is undoubtedly one of the common JavaScript frameworks used for front-end growth these days.

Many programming learners, like myself, have already delved into studying React.js, particularly these aspiring to turn out to be front-end builders.

Nevertheless, I’ve seen that the useMemo hook isn’t all the time utilized as a lot because the useState or useEffect hooks in net growth, though it does rely on the precise mission necessities.

Due to this fact, I’ve determined to put in writing an article introducing the essential utilization of the useMemo hook, a built-in React hook, for individuals who will not be aware of it.



What’s useMemo hook in React.js

useMemo is a React hook memorizing the results of a perform name (returned worth from a perform). And this memorization is useful for optimizing the efficiency of net purposes.

useMemo wraps a perform in it and that perform isn’t triggered till the worth outlined at dependencies of useMemo has been modified.

In different phrases, useMemo computes solely when considered one of its dependencies is up to date with a purpose to keep away from pointless calculations.



How useMemo works

To display the mechanism of useMemo hook, here’s a pattern code snippet;

// Baby element

import { useMemo } from "react";

const Baby = ({ a:quantity, b:quantity }) => {
  // Callback perform returning the sum of a and b
  const sum = useMemo(() => {
    // Test if Baby element is rendered
    console.log("Baby element is rendered");
    return a + b;
  // array of dependencies ([a,b])
  }, [a, b]);
  return <div>No. {sum}</div>;
};

export default Baby;
Enter fullscreen mode

Exit fullscreen mode

As you may see, there are two React perform elements whose names are Father or mother and Baby. Within the Baby element, useMemo is used and has the next two arguments;

  • Callback perform that returns the sum of two parameters (‘a’ and ‘b’)
  • Array of dependencies ([a,b]) that specify when useMemo ought to be fired

Now that we’ve these two arguments in useMemo, it’s potential to memorize the worth returned from the callback perform till one of many worth dependencies outlined in useMemo has been modified.

Consequently, because of the results of useMemo hook, we may optimize performances in our React purposes.



Let’s examine the circumstances with and with out useMemo hook

Within the earlier part, we may briefly study the fundamentals of how useMemo hook works. So let’s dive into a bit deeper facet of useMemo hook to grasp extra about the good thing about utilizing it.

Right here is one other code snippet with a element whose title is Father or mother element, containing the Baby element.


// Father or mother Part

import Baby from "./Baby";
import { useState } from "react";

const Father or mother = () => {
  // Declare React state for the counter
  const [count, setCount] = useState(0);

  // Outline two fixed variables which have numbers respectively
  const numA = 3;
  const numB = 40;

  // A perform that's triggered by onClick occasion in button element and increment the variety of counter by 1
  const handleAddCount = () => {
    setCount((prevState) => prevState + 1);
  };

  // Test if Father or mother element is rendered
  console.log("Father or mother element is rendered");

  return (
    <>
      <div type={{ paddingTop: "2rem" }}>
        <p>Quantity in Baby element</p>
        {/* Go two variables (numA and numB) as props to the Baby element */}
        <Baby a={numA} b={numB} />
      </div>
      <div type={{ paddingTop: "4rem" }}>
        <p>Rely quantity: {rely} counts</p>
        {/* Set onClick occasion to increment the counter by 1 */}
        <button onClick={handleAddCount}>ADD</button>
      </div>
    </>
  );
};

export default Father or mother;
Enter fullscreen mode

Exit fullscreen mode

Within the Father or mother element, there’s a counter carried out by counter state and setCounter perform with React state. So each time I click on the “ADD” button, the variety of counter displayed might be incremented by 1.



Case1: With useMemo hook

And the Baby element in Father or mother element is identical element that’s outlined above.

// Baby element (with useMemo)

import { useMemo } from "react";

const Baby = ({ a:quantity, b:quantity }) => {
  // Callback perform returning the sum of a and b
  const sum = useMemo(() => {
    // Test if Baby element is rendered
    console.log("Baby element is rendered");
    return a + b;
  // array of dependencies ([a,b])
  }, [a, b]);
  return <div>No. {sum}</div>;
};

export default Baby;
Enter fullscreen mode

Exit fullscreen mode

So now, to illustrate I click on the ADD button within the Father or mother element, and what is going to occur within the console?

As you may see the screenshot under, the counter is incremented to five. On the identical time, because of the impact of useMemo hook, though each time the ADD button is clicked (to replace the React state of counter within the Father or mother element), solely the Father or mother element is rendered. (Baby element isn’t re-rendered in any respect).

Image description



Case2: With out useMemo hook

Now that we may be certain that the benefit of utilizing useMemo hook to keep away from re-rendering in Baby element.

So what if I modify the portion of codes in Baby element and take away useMemo hook in it, what is going to occur?

If the useMemo hook is eliminated in Baby element, it might seem like this;

// Baby element (with out useMemo hook)

const Baby = ({ a:quantity, b:quantity }) => {
  const sum = a + b;
  // Test if Baby element is rendered
  console.log("Baby element is rendered");
  return <div>No. {sum}</div>;
};

export default Baby;
Enter fullscreen mode

Exit fullscreen mode

After which, once I did the identical factor in Case1 (Clicking the ADD button in mother or father element), the results of console is on this screenshot.

Image description

Now it turned out that with out useMemo hook in Baby element, Baby element is all the time re-rendered when the counter state in Father or mother element is up to date.

Contemplating higher performances in React purposes, it’s certain that we should always make the most of useMemo hook successfully.



Conclusion

The useMemo hook performs an important function in optimizing React purposes by memorizing values and stopping pointless renderings.

As a Entrance-Finish Developer specializing in React.js, successfully using the useMemo hook has helped me advance my expertise. I plan to discover it additional and combine it into my private initiatives throughout refactoring.

Moreover, there’s one other React hook, useCallback, which serves the same objective. Within the close to future, I intend to put in writing an article summarizing the essential utilization of the useCallback hook as properly.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?