top of page
dp.jpg

Hi, thanks for stopping by!

Hope you are getting benefitted out of these articles. Don't forget to subscribe to the Newsletter where we will serve you with the curated content right at your mailbox.

Let the posts
come to you.

Sponsor the Author.

React JS UseMemo, Performance Improvement.

React useMemo Hook is the standard hooks method, almost similar to Javascript memoisation.




In general, we use memoisation in javascript to cache specific data based upon the input provided to the function. The memoisation technique is generally used if you are willing to avoid heavy computations.


What is the use of useMemo in react?

Many functions are making heavy computational calculations, which can lead to reducing the performance of the entire code. Here comes the useMemo comes as a saviour.


React UseMemo (Example)



import React, { useMemo } from 'react';

function ChildComponent({ a, b }) {

  const heavlyComputationValue = useMemo(() => {
    console.log('Inside heavlyComputationValue value...');
    // Perform some expensive calculation based on props a and b
    return a + b;
  }, [a, b]);

  return (
    <div>
      <p>Heavly Computation Value: {heavlyComputationValue}</p>
    </div>
  );
}

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

  const increment = () => {
    setCount(prevCount => prevCount + 1);
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
      <ChildComponent a={count} b={10} />
    </div>
  );
}
  

Here in the program above you can see, we have created ChildComponent which has a function name as heavlyComputationValue. This function is ideally considered to have done some heavy computation before returning the result.


Now we want to make sure that the calculation is only done when some new props, are served to the function, else the magic of caching should return the result.


The calculation based upon the given props in dependency array, is cached. The result will be calculated for the first time, and rest if the same input is served to the function it will return the output upfront.


Let's try to understand the process of caching, although this is not the way React does the same. The code for it can be easily found at https://github.com/facebook/react . We can easily clone the repository and can understand the actual way.


Code caching for JavaScript? Caching Example



const cache = {};  
function getCachedData(key) {   
    if (cache[key]) {     
        console.log('Returning cached data');     
        return cache[key];   
    }

    console.log('Fetching data from server');
    const data = key;   
    cache[key] = data;    
    return data;
}

Here we have created a cache object, which will do all the hard work.


Whenever we are calling this function with an argument, we are keeping the value on the cache. Now whenever we are calling the function again, we first check in the cache object. If the input is being stored earlier, we return the response upfront.


If that is not the case we make an API call or the calculation. Post the calculation we can store the value as the output. As this is the custom logic, we can write a more specific use case. But something similar is done when caching is implemented.


This is an introduction to the React useMemo hook can be used. Also, we have discussed what is caching and an example of how it works.


 


About The Author

Apoorv Tomar is a software developer and blogs at Mindroast. You can connect with him on Twitter, Linkedin, Telegram, and Instagram. Subscribe to the newsletter for the latest curated content. Don’t hesitate to say ‘Hi’ on any platform, just stating a reference of where did you find my profile.




6 views
bottom of page