Memoization is a technique that is used to store(cache) value of a function call which is expensive, thereby not to make the same function call again if called with same arguments.
In this article, we will be discussing two of the memoizing techniques -memo and useMemo().
React.memo()
React memo is an HOC [Higher order component], it doesn’t re-render the component if passed with same props, thereby using the result of last render and enhance performance. It will re-render only if one of the prop has changed.
Now, let us jump to the implementation part ⬇
App.js
[React] import React, { useState } from “react”; import MemoComp from “./memoComp”; import “./styles.css”; export default function App() { const [itemCount, setItemCount] = useState(0); const [memoCount, setMemoCount] = useState(0); return (😀React memo Example😀
Home Count {itemCount}
memoComp.js
[React] import React, { memo } from “react”; const MemoComp = (props) => { const { memoCount } = props; console.log(“Memo Component”, memoCount); return (Memo Component
http://sh017.hostgator.tempwebhost.net/media/edf3b63b77f2f7879d55ce0f6f058971memo
In the above example, <MemoComp> component is not re-rendered if we click on “home” button, as the value of prop “memoCount” doesn’t change.
As <MemoComp> is wrapped with memo(), therefore it will only re-render if it’s prop i.e. memoCount changes.
useMemo()
useMemo() is a React hook. It returns memoized value and the function wrapped in it re-renders only if the value in it’s dependency array have changed. It is used for performance improvement. useMemo() can be used in case of an expensive/heavy computation function.
Let’s see the implementation ⬇
App.js
[React] import React, { useState, useMemo } from “react”; import “./styles.css”; export default function App() { const [counter1, setCounter1] = useState(0); const [counter2, setCounter2] = useState(0); const counterMemo = useMemo(() => { console.log(“In counter function”); return counter2 * 10; }, [counter2]); return (😀React useMemo😀
Counter 1 : {counter1}
Counter 2 : {counter2}
useMemo : {counterMemo}
http://sh017.hostgator.tempwebhost.net/media/6037e943c4b4b5bee5c6e0902f63306auseMemo
In the above example, we have wrapped “counterMemo” inside useMemo() and added “counter2” in the dependency array, so it is re-computed only if the value of “counter2” changes, thus optimizing it. If we do not use useMemo() here, the function would have been computed even if have changed the value of “counter1”.
Final Code
Hope this article was helpful.
You can go through the final code:
Thank You
Keep Learning🤓