-
useMemois a React build-in Hook that optimizes performance by caching (memorizing) the calculated result of a function between component re-renders instead of running a piece of logic on every single render React reuse the cached value useless its specific dependencies change.
Syntax :
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
The first argument is a function that returns the computed value.
The second argument is an array of dependencies. When any of these dependencies change, the function gets re-evaluated.
PROGRAM
import { useState, useMemo } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
const [arr, setArr] = useState([7, 8, 9, 10])
const showMax = useMemo(() => {
return(Math.max(...arr))
}, [arr])
function addMax() {
setArr([...arr,count + 5])
console.log(arr);
}
return (
<div>
<h3>Count = {count}</h3>
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={addMax}>Add New</button>
<h5> Max Value = {showMax} </h5>
</div>
)
}
export default App
OUTPUT


Top comments (0)