Benefits of useMemo() :-
- when you want to make slow Function we wrap it in this useMemo() hook so that doesn't recompute every single time you render your component and it only computes when you actually need the value from that function since the inputs actually changed
- referencial equality - whenever you want to make sure the reference of an object or an array is exactly same as it was the last time you rendered if none of the internal workings changed you're gonna want to use useMemo() here to make sure that you only update the reference of that object whenever the actual contents of the object changed instead of updating every single time you render.
App.js Code :-
import { useState, useEffect, useMemo } from 'react';
export default function App() {
const [number, setNumber] = useState(0);
const [dark, setDark] = useState(true);
function slowFunction(num) {
console.log("in function");
for (let i = 0; i <= 1000000000; i++) { };
return num * 2;
};
// const doubleNumber = slowFunction(number);
const doubleNumber = useMemo(() => {
return slowFunction(number);
}, [number]);
const themeStyles = useMemo(() => {
return {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
}, [dark]);
useEffect(() => {
console.log("theme changed");
}, [themeStyles]);
return (
<>
<input type="number" value={number} onChange={e => setNumber(parseInt(e.target.value))} />
<button onClick={() => setDark(prevDark => !prevDark)}> Change Theme </button>
<div style={themeStyles}> {doubleNumber} </div>
</>
)
}
Top comments (0)