Understanding React useMemo Hook With Example

July 07, 2023
Understanding React useMemo Hook with Example



Learning to optimize your applications for performance can make you a better developer overnight. In React, there are many hooks you can use to elevate the speed and performance of your apps, however, not many can defeat the utility of the React useMemo hook.

The useMemo hook caches or saves the output in the system memory and recalls it the next time, relatively fast, when prompted to do so. For instance, when you request a system to perform lengthy calculations, the React useMemo hook caches its answer in its memory. So, the next time you do the same, the system won’t have to re-process or re-calculate.

react dev jobs

The Syntax

The useMemo hook works with two arguments, including functions array and dependencies. Let’s review a React useMemo example below to understand better how it works in real time.

import "./styles.css";

import { useMemo } from "react";

export default function App() {

  const memodVal = useMemo(

    () => {/* Function */},

    [/* Dependency List */]

  );

  return (

    <div className="App"></div>

  );

}

React useMemo Example

import "./styles.css";

import { useState, useMemo } from "react";




export default function App() {

  const [grade, setGrade] = useState(7);

  const countPopulation = ((grade) => {

    return grade ** 2;

  });

  const memoizedVal = useMemo(() => countPopulation(grade), []);

  return (

    <div className="App">

      <p>Current Grade: {grade}</p>

      <p>Current Population: {memoizedVal}</p>

    </div>

  );

}

Output:

React useMemo Example

React useMemo vs. useCallback

The useMemo hook is not the only one used to cache results in memory for later use and React useCallback works in much the same way. Both use cache memorization to get the job done.

However, there lies a difference between the two. Reach useCallback memorizes the function, while the useMemo hook only stores the output. Let’s review a React useMemo example below.

React useMemo()

import "./styles.css";

import { useState, useMemo } from "react";

export default function App() {

  const [grade, setGrade] = useState(4);

  const countPopulation = (grade) => grade ** 2;

  const memoizedVal = useMemo(() => countPopulation(grade), [grade]);

  return (

    <div className="App">

      <RenderVal grade={grade} val={memoizedVal} />

    </div>

  );

}

const RenderVal = ({ grade, val }) => {

  return (

    <>

      <p>Current Grade: {grade}</p>

      <p>

        Current Population: {' '}

        {typeof val === 'function' ? val() : val}

      </p>

    </>

  );

};

React useCallback()

import "./styles.css";

import { useState, useCallback  } from "react";

export default function App() {

  const [grade, setGrade] = useState(4);

  const countPopulation = countPopulation(grade), [grade]);

  const memoizedCallback = useCallback (() => countPopulation(grade), [grade]);

  return (

    <div className="App">

      <RenderVal grade={grade} val={memoizedCallback} />

    </div>

  );

}

const RenderVal = ({ grade, val }) => {

  return (

    <>

      <p>Current Grade: {grade}</p>

      <p>

        Current Population: {' '}

        {typeof val === 'function' ? val() : val}

      </p>

    </>

  );

};

Output:

React useCallback()

 

The above React useMemo example illustrates how similar its syntax is to React useCallback. Here the only difference is the latter returns a function while the former returns a value.

When to use React useMemo()?

Hooks like React useMemo lures developers to go overboard and sprinkle them anywhere they can. However, it is best to use any hook using memorization like React useMemo and React useCallback with moderation, as too many recalls can impact performance.

As a rule of thumb, it is best to write the code first and then turn to optimize for performance using React useMemo. Moreover, it is advisable to use profiling tools to identify expensive elements before enforcing performance upgrades. Here, the term expensive implies those which take up more than average resources or memory.

Conclusion

React useMemo hooks help you improve your application’s performance and develop performance-oriented apps. However, it is a must to practice caution and moderation, as using too many hooks does more harm than good.

Also Read: Functional Programming In Python: When And How To Use It?

react jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US