React Hooks — useMemo Hook In ReactJS

  1. useMemo()

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
Memoization is the optimized technique used primarily to speed up computer programs by storing up results of the expensive function calls and returning cache results when the same input occurs.
The useMemo hook serves a similar purpose like useCallback , useMemo returns a memoized value instead of a function reference. This allows you to avoid repeatedly performing potentially costly operations until necessary. The useMemo Hook typically returns a cached value until a dependency gets changed. If a dependency gets changed, React will re-do the expensive calculation and update the memoized value.

Look at the following code that does a costly calculation with one state field:

import { useState } from 'react';
function slowFunction(number) {
 for (let i; i < 11111111111111; i++) {}
 return number * 3;
}
const Example = () => {
 const [dark, setDark] = useState(false);
 const [number, setNumber] = useState(0);

 const trifleNumber = slowFunction(number);

 const themes = {
  backgroundColor: dark ? 'black' : 'white',
  color: dark ? 'white' : 'black',
  marginBottom: '10px',
 };
 const handleChangeThem = () => {
  setDark((prevDark) => !prevDark);
 };
 return (
  <>
   <h1>Welcome to React Hook UseMemo</h1>
   <div>
    <input
     value={number}
     type='number'
     placeholder='Enter a number'
     onChange={(e) => {
      setNumber(e.target.value);
     }}
    />
   </div>
   <div>
    <button onClick={handleChangeThem}>Change the theme</button>
   </div>
   <div style={themes}>{trifleNumber}</div>
  </>
 );
};
export default Example;

The above code implements two main functional segments in the app:

  • Change in the input number and triple number

  • Change the theme to dark or white

Once you run the app, it will work as expected. whenever the number changes, slowFunction that takes a number parameter. which simulates a slow computation. It multiplies the number parameter by 3 and returns the result. when you click on the change theme button slowFunction
also get triggered.
There is a hidden issue. when you click on the Change Theme button, the app works slowly because the slowFunction triggered which is a costly operation.

The reason is that when a change in the number slowFunction also triggers so there will be a delay in printing the triple number, As a solution, we can wrap the slowFunctionfunction call with useMemo to let React use a cache value when the Example component re-renders when there is no change in the number

const trifleNumber = useMemo(()=>slowFunction(number), []);

Now, the useMemo Hook calculates a trifle Number number only if the number dependency gets changed, so the Change Theme will work faster! You can check out the optimized example here:

import { useMemo, useState } from 'react';
function slowFunction(number) {
 for (let i; i < 11111111111111; i++) {}
 return number * 3;
}
const Example = () => {
 const [dark, setDark] = useState(false);
 const [number, setNumber] = useState(0);

 // with useMemo
 const trifleNumber = useMemo(() => {
  return slowFunction(number);
 }, [number]);

 const themes = {
  backgroundColor: dark ? 'black' : 'white',
  color: dark ? 'white' : 'black',
  marginBottom: '10px',
 };
 const handleChangeThem = () => {
  setDark((prevDark) => !prevDark);
 };
 return (
  <>
   <h1>Welcome to React Hook UseMemo</h1>
   <div>
    <input
     value={number}
     type='number'
     placeholder='Enter a number'
     onChange={(e) => {
      setNumber(e.target.value);
     }}
    />
   </div>
   <div>
    <button onClick={handleChangeThem}>Change the theme</button>
   </div>
   <div style={themes}>{trifleNumber}</div>
  </>
 );
};
export default Example;

Conclusion

The useMemo function is an instrument for fine-tuning React. Knowing how and when to use each could potentially improve application performance. Still, no inbuilt performance-improvement Hook is a substitute for a poorly written React app codebase. In this blog, we have provided a guide for understanding how to use these tools, but keep in mind that using them comes with a cost (memory usage for caching).

0
Subscribe to my newsletter

Read articles from NonStop io Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

NonStop io Technologies
NonStop io Technologies

Product Development as an Expertise Since 2015 Founded in August 2015, we are a USA-based Bespoke Engineering Studio providing Product Development as an Expertise. With 80+ satisfied clients worldwide, we serve startups and enterprises across San Francisco, Seattle, New York, London, Pune, Bangalore, Tokyo and other prominent technology hubs.