Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Mon May 15 2023

How useMemo works in React

In this article, we will explain and show examples of how useMemo in React is used.

useMemo is an optimization hook in React that will cache a previous result of a function, so that it doesn't need to be executed on every render. It is very handy when we have expensive calculations or similar that we don't want to be called if not necessary. The function will only be called if any of the dependencies has changed.

Related topis:

Example

Below we will show an example of how useMemo can be used. We will have a state variable that will be a dependency to our useMemo hook. And as long as that number doesn't change, the return value will be cached.

import { useMemo, useState } from "react"; const MyComponent = () => { const [number, setNumber] = useState(0); const multipliedNumber = useMemo(() => { return number * 2; }, [number]); return <div>{multipliedNumber}</div>; };

And that's it. Now our multipliedNumber will have the same value and not be re-calculated for every render, until the state variable number is changed.

Outro

In this short guide, we showed how to use useMemo in React. I personally use this a lot and my personal take is that we should do our best to keep the code optimized and efficient, and useMemo and useCallback are great ways of helping out with that.

Thanks for reading, and have a great day!

signatureMon May 15 2023
See all our articles